您好,我正在尝试从 C 字符串中删除一个字符,但输出似乎不正确。如果例如。 输入字符串 = "你好" 要删除的指定字符 = "l" 我的输出是“HeXXo”。我似乎需要在删除字符后将值插入?
代码如下:
#include <stdio.h>
#include <stdlib.h>
void squeeze(char str[], char c);
void main (){
char input[100];
char c;
printf("Enter string \n");
gets(input);
printf("Enter char \n");
scanf("%c", &c);
printf("char is %c \n", c);
squeeze(input , c );
getchar();
getchar();
getchar();
}
void squeeze(char str[], char c){
int count = 0, i = 0;
while (str[count] != '\0'){
count++;
}
printf("Count = %d \n", count);
for ( i = 0 ; i != count; i++){
if (str[i] == c){
printf("Found at str[%d] \n", i);
str[i] = "";
}
}
printf(" String is = %s", str);
}
最佳答案
str[i] = "";
您正在尝试分配一个指针而不是一个字符。您的意思可能是 ' '
但这也不是从字符串中删除字符的正确方法,而是替换它们。尝试:
char *p = str;
for (i = 0 ; i != count; i++) {
if (str[i] != c)
*p++ = str[i];
}
*p = 0;
编辑
这里有一个我比较喜欢的解决方案:
char *p = s; /* p points to the most current "accepted" char. */
while (*s) {
/* If we accept a char we store it and we advance p. */
if (*s != ch)
*p++ = *s;
/* We always advance s. */
s++;
}
/* We 0-terminate p. */
*p = 0;
关于c - 如何从字符串中删除所有出现的特定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19241982/