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?
Printable View
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'.
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) ;