gpt4 book ai didi

c - 如何用一个字符替换两个字符?

转载 作者:行者123 更新时间:2023-12-03 13:56:18 25 4
gpt4 key购买 nike

所以我试图替换 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. Here strstr(str, "cc") could have helped.

关于c - 如何用一个字符替换两个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64840869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com