c - C语言中删除字符串中的字母

标签 c arrays string pointers

我被指派构建代码,执行以下操作: 要求用户输入一个单词(最多 30 个字母),然后删除所有“A,a,O,o”字母并打印,不带任何空格。例如:输入:OkleaAo,输出:kle

有人告诉我,更简单的方法是使用 2 个数组,并使用 IF 循环,将不是 A/a/o/O 的字母添加到第二个数组,然后打印它。

我现在真的陷入困境,我知道我必须使用指针,但它不起作用。 有什么帮助、建议吗?

我写了这样的内容:

#include <stdio.h>

char input[30], *p;
char output[30];

main()
{
    printf("Enter a string:\n", input);
    scanf("%s", input);
    if *(p==o);
    {
        *p=0;
        printf("String after deletion:", input);
    }

}

最佳答案

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

int main(){
    char input[30+1];
    char output[30+1];
    int i, j;

    printf("Enter a string :");
    scanf("%30[^\n]", input);

    for(j = i = 0;input[i];++i){
        char *p, ch = input[i];
        p = strchr("AaOo ", ch);
        if(p == NULL)
            output[j++] = ch;
    }
    output[j] = '\0';
    printf("\nString after deletion: %s\n", output);
    return 0;
}
<小时/>
#include <stdio.h>

int main(){
    char input[30+1];
    char *in, *out;

    printf("Enter a string :");
    scanf("%30[^\n]", input);

    out = in = input;
    while(*in){
        char ch = *in;
        if(ch != 'A' && ch != 'a' && ch != 'O' && ch != 'o' && ch != ' ')
            *out++ = *in;
        ++in;
    }
    *out = '\0';
    printf("\nString after deletion: %s\n", input);
    return 0;
}

关于c - C语言中删除字符串中的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970653/

相关文章:

c# - 如何在字符串中搜索单词(只是单词)?

javascript - 获取列表项 Javascript 内列表项的值

c++ - 如何在字符串 vector 中引用字符串的特定字符?

python字符串在单引号前添加反斜杠

c - C-- 与 LLVM 相比如何?

arrays - 如何比较 C 中由 strdup() 创建的两个字符串数组?

php - 可能的 ? : mysql row to an if condition

C 循环和转到

c++ - 查看是否可以使用堆栈从左侧和右侧以相同的方式读取字符串

c - 为什么我的代码会出现 "nested functions are disabled..."错误?