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/