所以,我想创建一个函数,它创建并返回一个基于字符串s 的动态字符串,不带字符c。现在,我希望能够删除所有需要的字符,无论如何。此外,用户输入的原始字符串应保持不变。这是我的尝试,它一直告诉我第 12 行的错误(在评论中注明)。
还有一件事:我不确定我是否将remove 函数写得很好,我认为它应该可以工作?所有的指针都让我有点困惑。
#include <stdio.h>
#include <stdlib.h>
char * remove(char *s, char c);
int strlen(char *s);
int main() {
char s[16], c, n[16];
printf("Please enter string: ");
scanf("%s", s);
printf("Which character do you want to remove? ");
scanf("%c", &c);
n = remove(s, c); // Place the new string in n so I wouldn't change s (the error)
printf("The new string is %s", n);
return 0;
}
int strlen(char *s)
{
int d;
for (d = 0; s[d]; d++);
return d;
}
char * remove(char *s, char c) {
char str[16], c1;
int i;
int d = strlen(s);
str = (char)calloc(d*sizeof(char)+1);
// copying s into str so I wouldn't change s, the function returns str
for (i = 0; i < d; i++) {
while(*s++ = str++);
}
// if a char in the user's string is different than c, place it into str
for (i = 0; i < d; i++) {
if (*(s+i) != c) {
c1 = *(s+i);
str[i] = c1;
}
}
return str; // the function returns a new string str without the char c
}
最佳答案
您将 n
声明为 char 类型的 16 元素数组:
char n[16];
所以你不能这样做:
n = remove(s, c);
因为 n
是一个常量指针。
此外,您的 remove
函数会返回一个指向其本地数组的指针,该数组会在您的函数返回后立即销毁。最好将 remove
声明为
void remove(char *to, char *from, char var);
并将n
作为第一个参数传递。
关于c - 使用动态字符串从 C 中的字符串中删除一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105934/