所以我试图替换 cc
与 &
在一个句子中(例如: "Hi this is Mark cc Alice"
)。到目前为止,我有这个代码替换第一个 c
与 &
但是第二个 c
还在。我将如何摆脱第二个 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;
}
输入是:Hi this is Mark cc Alice
输出是:Hi this is Mark &c Alice
最佳答案
您可以使用通用的“后移”功能将其移动到一个位置:
void shunt(char* dest, char* src) {
while (*dest) {
*dest = *src;
++dest;
++src;
}
}
您可以像这样使用它的地方: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;
}
注意从凌乱的 int
的切换声明 + while
+ 加一 for
环形。使用 char*
会更简洁指针代替:for (char* s = str; *s; ++s) {
if (s[0] == 'c' && s[1] == 'c'){
*s = '&';
shunt(&s[1], &s[2]);
}
}
使用 C 字符串时,使用指针很重要,因为这可以为您节省很多麻烦。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.
关于c - 如何用一个字符替换两个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64840869/