c - 使用指针重写代码

标签 c pointers

void rmchr(char*string, char ch) //string function
{
   int i; //position in string variable
   int j; //updated variable of i to the end of string
   for(i=0; string[i] != '\0'; i++) // i iterates through the string
   {
      if(string[i] == ch) //checks if given character is equal to char at ith position
      {
         for(j=i; string[j] != '\0'; j++) //loop from i to end of string
         {
            string[j] = string[j + 1]; //swaps value of next char so matching char is placed at end of string
         }
         string[j] = '\0';
         i--; //decrease i by 1
      }
   }
}

I need this code to be rewritten using pointers. Please help. The program takes a string and a character and removes all occurrences of the character from the string. I haven't included all code as this is the only code that needs to be rewritten using pointer arithmetic.

最佳答案

您可以通过递增指针(而不是使用数组查找)来进行迭代。然而,在许多情况下,编译器将能够优化这两个版本以获得相似的性能。

for (char *p = string; *p; ++p) {
    if (*p == ch) {
        for (char *q = p; *q; ++q) {
            *q = *(q + 1);
        }
    }
}

关于c - 使用指针重写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51164151/

相关文章:

c - 我不了解C字符串

C:指针和数组

c++ - 一元 ‘*’ 的无效类型参数(有 ‘int’ )

c - 在mex文件matlab中使用magma_dysevd

python - PJSUA 使用 c 进行 sip 注册时出错

c - 在内存中发现程序的图像

objective-c - Objective-C 中的指针和数据分配

c++ - 传递给函数时如何使结构为空?

c - 为什么下面的C代码是非法的?

C, 限制一个数字到 <= 64 的快速方法