使用动态字符串从C中的字符串中删除字符

时间:2016-01-30 19:14:30

标签: c string dynamic

所以,我想创建一个创建并返回的函数,该函数基于字符串 s 而不包含字符 c 。现在,我希望能够删除所有想要的字符,无论如何。此外,用户输入的原始字符串应保持不变。这是我的尝试,它一直告诉我第12行的错误(在评论中注明)。

还有一件事:我不确定我是否写好删除功能,我认为它应该有用吗?所有的指针都让我感到困惑。

#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
}

2 个答案:

答案 0 :(得分:4)

您将n声明为char类型的16元素数组:

char n[16];

所以你做不到:

n = remove(s, c);

因为n是一个常量指针。

此外,您的remove函数返回指向其本地数组的指针,该函数会在函数返回后立即销毁。最好将remove声明为

void remove(char *to, char *from, char var);

并将n作为第一个参数传递。

答案 1 :(得分:1)

在您的程序中存在很多错误,通过添加注释更容易重写并向您显示。请注意,scanf("%s...只接受一个单词,而不是句子(它在第一个空格处停止)。请注意,除非您按照建议添加空格,否则newline将保留在输入缓冲区中以便scanf("%c...读取。

#include <stdio.h>

void c_remove(char *n, char *s, char c) {   // renamed because remove() is predefined
    while (*s) {                            // no need for strlen()
        if (*s != c)                        // test if char is to be removed
            *n++ = *s;                      // copy if not
        s++;                                // advance source pointer
    }
    *n = '\0';                              // terminate new string
}

int main(void) {                            // correct signature
    char s[16], c, n[16];
    printf("Please enter string: ");
    scanf("%s", s);
    printf("Which character do you want to remove? ");
    scanf(" %c", &c);                       // the space before %c cleans off whitespace
    c_remove(n, s, c);                      // pass target string pointer too
    printf("The new string is %s", n);
    return 0;
}

计划会议:

Please enter string: onetwothree
Which character do you want to remove? e
The new string is ontwothr

Please enter string: onetwothree
Which character do you want to remove? o
The new string is netwthree