我试图从C中的字符串中删除一个字符.我的代码问题是它从字符串中删除了字符的第一个实例,但也擦除了字符串中该字符后的所有内容.例如,从'hello'中删除'l'会打印'he'而不是'heo'
int i;
char str1[30] = "Hello", *ptr1, c = 'l';
ptr1 = str1;
for (i=0; i<strlen(str1); i++)
{
if (*ptr1 == c) *ptr1 = 0;
printf("%c\n", *ptr1);
ptr1++;
}
Run Code Online (Sandbox Code Playgroud)
我需要使用指针,并希望尽可能简单,因为我是C的初学者.谢谢
das*_*ght 25
你可以这样做:
void remove_all_chars(char* str, char c) {
char *pr = str, *pw = str;
while (*pr) {
*pw = *pr++;
pw += (*pw != c);
}
*pw = '\0';
}
int main() {
char str[] = "llHello, world!ll";
remove_all_chars(str, 'l');
printf("'%s'\n", str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是保持一个单独的读写指针(pr
用于读取和pw
写入),始终使读取指针前进,并且只有当指针指向给定字符时才推进写入指针.