C,比较数组,找到一个字符,

时间:2016-12-10 13:57:54

标签: c

所以我对编码有点新意,但我想要做的是写一个字符串,写一个我希望不会出现在字符串中的字符。我尝试使用removedChar = getchar()代替fgets(removedChar, 2, stdin);,但我无法在!=语句中执行if

我真的很感谢你的帮助。

int main() {
    char str[20], removedChar[2];
    int i, n, j;

    printf("ENTER A STRING:");
    fgets(str, 20, stdin);
    printf("ENTER WHAT CHAR YOU WISH TO REMOVE: ");
    fgets(removedChar, 2, stdin);

    n = strlen(str);
    for (i = 0, j = 0; i < n; i++) {
        if (strcmp(str, removedChar) == 0) {
            str[j] = str[i];
            j++;
        }
        if (str[i] == ' ') {
            str[j] = str[i];
            j++;
        }
    }
    str[j] = '\0';
    printf("string after removing character = %s", str);

    system("pause");

    return 0;
}

2 个答案:

答案 0 :(得分:2)

首先是这一行:

if (strcmp(str, removedChar) == 0)

比较两个字符串是否相同。请参阅strcmp

您需要将字符与字符进行比较,而不是将字符串与字符串相等。

说完这个之后,你现在可以简单地循环遍历字符串,并使用!=来排除匹配的字符,并使用计数器相应地更新字符串。

此外,检查fgets的返回值始终是安全的,并检查您是否已超过缓冲区长度。

这是使用这些想法的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STRSIZE 20

int
main(int argc, const char *argv[]) {
    char str[STRSIZE];
    int i, j, removedchar;
    size_t slen;

    printf("Enter a string: ");
    if (fgets(str, STRSIZE, stdin) == NULL) {
        printf("Error reading string\n");
        return 1;
    }

    slen = strlen(str);

    if (slen > 0) {
        if (str[slen-1] == '\n') {
            str[slen-1] = '\0';
        } else {
            printf("Error: Exceeded Buffer length of %d.\n", STRSIZE);
            return 1;
        }
    }

    if(!*str) {
        printf("Error: No string entered.\n");
        return 1;
    }

    printf("Enter what character you wish to remove: ");
    removedchar = getchar();

    if (removedchar == '\n') {
        removedchar = ' ';
        printf("No character was entered. Spaces will be removed if found\n");
    }

    j = 0;
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] != removedchar) {
            str[j++] = str[i];
        }
    }
    str[j] = '\0';

    printf("Changed String = %s\n", str);

    return 0;
}

答案 1 :(得分:1)

您应该使用str[i] != removedChar[0]而不是使用比较完整字符串的strcmp()

另请注意,您应该从fgets()读取的字符串中删除换行符。

以下是更正后的版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char str[80], removedChar[80];
    int i, n, j;

    printf("ENTER A STRING: ");
    if (!fgets(str, sizeof str, stdin))
        return 1;
    str[strcspn(str, "\n")] = '\0';  // strip the newline character if present

    printf("ENTER WHAT CHAR YOU WISH TO REMOVE: ");
    if (!fgets(removedChar, sizeof removedChar, stdin))
        return 1;

    for (i = 0, j = 0; str[i] != '\0'; i++) {
        if (str[i] != removedChar[0]) {
            str[j] = str[i];
            j++;
        }
    }
    str[j] = '\0';
    printf("string after removing character = %s\n", str);

    system("pause");

    return 0;
}
相关问题