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

标签 c loops char c-strings

所以我试图替换 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/

相关文章:

c - 4 个子进程之间的管道通信仅在第一次有效

javascript - 如何循环 jQuery 代码?

excel - 选择直到不等范围

char数组到uint8类型指针的转换

c - "static char"与 C 中的 "char"

c - 在冒泡排序中使用第二个for循环

c - 与 C 中的链表有点混淆

c - 编译 C 程序时出错

c - 这个循环是无限的,但它不应该是 - C

java - 如何用 ' ' 声明 int?为什么 '2' == 50?