I want to take all of a specific letter from a string and insert another letter were the old ones were i just cant figure out how.For example say you enter the string "goodbye" and i want to change all the o's to a's how would i do that?
I want to take all of a specific letter from a string and insert another letter were the old ones were i just cant figure out how.For example say you enter the string "goodbye" and i want to change all the o's to a's how would i do that?
Loop over the characters of the string. Whenever the current character is an 'o', assign an 'a'.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Here's an example:
Code:#include <stdio.h> #include <string.h> int main(void) { char str[] = "goodbye"; int str_len = strlen(str); int x; printf("BEFORE: %s\n", str); for(x = 0; x < str_len; x++) { if(str[x] == 'o') str[x] = 'a'; } printf("AFTER: %s\n", str); return 0; }
Another way to loop over a string using the fact that c strings are Null terminated:
And it retains the "spirit of the language" which strlen() does not.Code:for (i = 0;str[i] != '\0';++i) ;