Reputation: 149
For example, I choose a string "sdoeoeeoasd". I should replace all the 'o' with 'e' and vice versa: "sdeoeooeasd". I intend to do this with the string
lib.
I found a pretty similar question (Standard function to replace character or substring in a char array?), but I don't get how to make the code work according to my condition. It happens that the first occurence of the character is replaced, and then the only one character replaces:
char* replace_char(char* str, char find, char replace){
char temp = find;
char *current_pos = strchr(str,find);
char *current_posc2 = strchr(str,replace);
while (current_pos) {
*current_pos = replace;
current_pos = strchr(current_pos,find);
}
while (current_posc2) {
*current_posc2 = find;
current_posc2 = strchr(current_posc2, replace);
}
return str;
}
With c1='e'
and c2='o'
I get:
I have a thought about adding the third temp
variable, but my suggestions of its implementation were wrong and didn't work.
Upvotes: 0
Views: 838
Reputation: 412
there is no need to use two loops
char *replace_char(char *str, char find, char replace) {
char *ptr = str;
while (*ptr) {
if (*ptr == find) *ptr = replace;
else if (*ptr == replace) *ptr = find;
ptr++;
}
return str;
}
also you can use syntax array
int j=0;
while(str[j] !='\0') // will loop on your string till the end of it
{
if(str[j] == 'e') // if char=e will be o
str[j]='o';
else if(str[j] == 'o') // if char=o will be e
str[j]='e';
j++;
}
```````````````````````
Upvotes: 0
Reputation: 108978
Do one loop:
char *replace_char(char *str, char find, char replace) {
char *str2 = str; // save str for return value
while (*str2) {
if (*str2 == find) *str2 = replace;
else if (*str2 == replace) *str2 = find;
str2++;
}
return str;
}
Upvotes: 1
Reputation: 1655
Your code doesn't work because it replaces all of the first character with the second character, then replaces all of the second character with the first character. It completely undoes the work of the first step in the second step. It's much simpler to just iterate through the string one character at a time, like in Bouraoui Al-Moez L.A's code.
Upvotes: 1
Reputation: 989
Another solution:
int i=0;
while(ch[i])
{
if(ch[i] == 'e')
ch[i]='o';
else if(ch[i] == 'o')
ch[i]='e';
i++;
}
Upvotes: 3