c - 使用动态字符串从 C 中的字符串中删除一个字符

标签 c string dynamic

所以,我想创建一个函数,它创建并返回一个基于字符串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/

相关文章:

c - 警告 : incompatible implicit declaration of built-in function log2

C:strcat和strcpy函数如何实现?

AppleScript 中的字符串操作

c++动态二维数组不使用默认构造函数

java - 在Java中动态加载一个类

c - 在 CUDA 中使用常量内存和结构数组

c++ - 在 C/C++ 中检查 NULL 指针

c - 如何在 C 中传递 3 维数组的地址?

python - 在 Python 中将哈希字符串表示为二进制

c++ - 调用 delete[] 会破坏我的 C++ 程序