So I'm trying to replace cc
with &
in a sentence (eg: "Hi this is Mark cc Alice"
). So far I have this code where it replaces the first c
with &
but the second c
is still there. How would I get rid of the second c
?
int main() {
char str[] = "Hi this is Mark cc Alice";
int i = 0;
while (str[i] != '\0') {
if (str[i] == 'c' && str[i + 1] == 'c') {
str[i] = '&';
//str[i + 1] = ' ';
}
i++;
}
printf("\n-------------------------------------");
printf("\nString After Replacing 'cc' by '&'");
printf("\n-------------------------------------\n");
printf("%s\n",str);
return str;
}
The input is:
Hi this is Mark cc Alice
The Output is:
Hi this is Mark &c Alice
You can just shuffle it over one spot using a generic "move back" function:
void shunt(char* dest, char* src) {
while (*dest) {
*dest = *src;
++dest;
++src;
}
}
Where you can use it like this:
int main(){
char str[] = "Hi this is Mark cc Alice";
for (int i = 0; str[i]; ++i) {
if (str[i] == 'c' && str[i+1] == 'c') {
str[i]='&';
shunt(&str[i+1], &str[i+2]);
}
}
printf("\n-------------------------------------");
printf("\nString After Replacing 'cc' by '&'");
printf("\n-------------------------------------\n");
printf("%s\n",str);
// main() should return a valid int status code (0 = success)
return 0;
}
Note the switch from the messy int
declaration + while
+ increment into one for
loop. This would be even less messy using a char*
pointer instead:
for (char* s = str; *s; ++s) {
if (s[0] == 'c' && s[1] == 'c'){
*s = '&';
shunt(&s[1], &s[2]);
}
}
When working with C strings it's important to be comfortable working with pointers as that can save you a lot of hassle.
You should also familiarize yourself with the C Standard Library so you can use tools like
strstr
instead of writing your own equivalent of same. Herestrstr(str, "cc")
could have helped.
You have to shift the whole array to left. A simple way of doing that is :
#include <stdio.h>
#include <string.h>
#define STR_SIZE 25
int main(){
char str[STR_SIZE] = "Hi this is Mark cc Alice";
int i=0,j=0;
while(str[i]!='\0'){
if(str[i]=='c' && str[i+1]=='c'){
str[i]='&';
for (j=i+1; j<STR_SIZE-1; j++) /* Shifting the array to the left */
{
str[j]=str[j+1];
}
}
i++;
}
printf("\n-------------------------------------");
printf("\nString After Replacing 'cc' by '&'");
printf("\n-------------------------------------\n");
printf("%s\n",str);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With