需要从C中的字符串中删除字符

时间:2017-05-10 21:49:21

标签: c string

我需要编写一个以字符串和字符作为输入的程序,然后从字符串中删除所有该字符。问题是我需要使用相同的字符串来打印输出。我到目前为止所做的代码并没有删除任何内容,我不知道为什么。

#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 25


int main(void)
{
    char string[MAX_LENGTH];
    int character;
    int count, i, j;

    printf("Enter a string (max length 25): ");
    fgets(string, MAX_LENGTH, stdin);
    printf("Enter a character: ");
    scanf("%d", character);

    count = 0;
    for (i = 0; string[i] != '\0'; i++){
        while (string[i] == character){
            count ++;
            for (j = i; string[j] != '\0'; j++){
                string[j] = string[j+1];
            }
            string[j] = '\0';
        }

    }
    printf("Output String: %s", string);
    printf("Output Count: %d\n", count);
}

1 个答案:

答案 0 :(得分:0)

编译器很容易发现代码中的第一个问题:

library(ggplot2)
weight$linear <- predict(mod_linear)
weight$nonlinear <- predict(mod_nls)

ggplot(weight, aes(size, mass)) +
  geom_point() +
  geom_line(aes(y = linear), color = "red") +
  geom_line(aes(y = nonlinear), color = "blue")

如果您使用$ clang char.c char.c:15:17: warning: format specifies type 'int *' but the argument has type 'int' [-Wformat] scanf("%d", character); ~~ ^~~~~~~~~ 1 warning generated. 取代character的地址,您的代码将会编译但仍然无法正常工作。首先,将&character替换为%d,因为您需要%c而不是char,并相应地更新定义(int)。然后,如果你只需要输出输入字符串减去任何出现的指定字符,你可以通过简单地逐字遍历字符来获得它:

char character

输出:

#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 25


int main(void)
{
    char string[MAX_LENGTH];
    char character;
    int count, i, j;

    printf("Enter a string (max length 25): ");
    fgets(string, MAX_LENGTH, stdin);
    printf("Enter a character: ");
    scanf("%c", &character);
    printf("%s", "Output String: ");
    count = 0;
    for (i = 0; string[i] != '\0'; i++){
        if (string[i] != character) {
            putchar(string[i]);
            count++;
        }
    }

    printf("Output Count: %d\n", count);
}