作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我试图替换 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/
我是一名优秀的程序员,十分优秀!