Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

search and replace in a char*

Status
Not open for further replies.

bitwise

Programmer
Mar 15, 2001
269
US
What would be the best way in C to search through a char* and replace all occurances of a character with a substring. For example, I need to backslash (\) out some characters in a char* that could screw with execution. How would I replace all occurances of ' with \' - Example:

Orignal char*:
"cat's are joe's favorite animal";

New char*:
"cat\'s are joe\'s favorite animal";

Thanks,
-bitwise
 
Allocate enough memory to hold the result string (the original string with the backslashes).

Loop through each character in the original string. If the current character is one you need to precede with a backslash, write a backslash and the current character into the result string, otherwise, just write the current character into the result string.

Post your best attempt if you get stuck.

Russ
bobbitts@hotmail.com
 
Cool, that is no problem, I just wanted to know if that was the correct method for doing this type of thing or if there was a better way.

One More Thing:
Is there a good way to determine how many times a character appears in a char*, or do you have to loop through it a count the number of times the character occures?

Thanks,
-bitwise
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top