943,971 Members | Top Members by Rank

Ad:
  • C Code Snippet
  • Views: 2463
  • C RSS
0

replace a substring by a new substring.

by on Nov 9th, 2009
need to replace all occurences if substring by new string. below code replace first occurence but not other substrings present in input string.
C Code Snippet (Toggle Plain Text)
  1. fnReplaceString()
  2. {
  3. char acInpString[MAX_LENGTH],acOrig[MAX_LENGTH],acReplace[MAX_LENGTH];
  4. char *pcInpStringPtr = acInpString;
  5. char *pcOrigPtr = acOrig;
  6. char *pcReplacePtr = acReplace;
  7. char *pPos;
  8. int iRes = 0;
  9. int iCount = 0;
  10. fflush(stdin);
  11. system("clear");
  12.  
  13. /* gets the input string from user */
  14. GET_STRING(acInpString);
  15.  
  16. printf("\n Enter substring to be replaced\n");
  17. gets(acOrig);
  18.  
  19. printf("\n Enter Substring to be placed \n");
  20. gets(acReplace);
  21.  
  22. /* check if substring to be replaced is present in entered string by user */
  23. if(!(pPos=strstr(acInpString,acOrig)))
  24. {
  25. printf("\n SUBSTRING TO BE REPLACED NOT PRESENT IN GIVEN STRING \n");
  26. }
  27. else
  28. {
  29. char acTemp[MAX_LENGTH];
  30. strncpy(acTemp,pcInpStringPtr,pPos-pcInpStringPtr);
  31. sprintf(acTemp+(pPos-pcInpStringPtr), "%s%s", pcReplacePtr, pPos+strlen(pcOrigPtr));
  32. puts(acTemp);
  33.  
  34. }
  35. }
Message:
Previous Thread in C Forum Timeline: Help!!!!!
Next Thread in C Forum Timeline: open,read and write problem





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC