c - 编写从文本中删除所有数字的程序

标签 c arrays pointers c-strings

我想制作使用指针删除文本中所有数字的程序,例如当键盘输入是“ab1c9”时,程序结果仅是“abc”。所以我实际上考虑使用指针并使用没有数字结果的单词覆盖它,但它似乎不起作用:/并且我仍然对何时应该使用 * 或不使用 * 感到困惑
这个程序逻辑正确吗?.?

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

void deldigit(char* str) {
    int count = 0;

    while(*str != '\0') {
        if(*str >= '1' && *str <= '9')
            count++;
        else
            *(str - count) = *str; /* want this *str after increment to overwrite *(str-count) */
        str++;
    }

    *(str - count) = '\0';
    printf("%s", str);
}

int main() {
    char str[100];

    printf("inset word");
    scanf("%s", &str);
    deldigit(str);

    return 0;
}

最佳答案

您需要在循环后倒回 str,并且您不会删除字符串中的零,请更改为:

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

void deldigit(char *str)
{
    char *res = str;
    int count = 0;

    while (*str != '\0') {
        if (isdigit((unsigned char)*str)) {
            count++;
        } else {
            *(str - count) = *str;
        }
        str++;
    }
    *(str - count) = '\0';
    printf("%s", res);
}

int main(void)
{
    char str[100];
    char *ptr;

    printf("insert word: ");
    if (fgets(str, sizeof str, stdin)) {
        if ((ptr = strchr(str, '\n'))) {
            *ptr = '\0';
        }
        deldigit(str);
    }
    return 0;
}

切换到fgets以避免缓冲区溢出。

关于c - 编写从文本中删除所有数字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225365/

相关文章:

c - 在简单菜单代码中的 while 循环期间卡住

c# - 如何为 C# 应用程序创建 RPC 服务器

c - 使用 strlen 和函数查找字符串长度。用空字符串打印

c# - 在 C# 中模拟 C 数据类型

arrays - 两个数组 LISP 的两个值之和

java - 在Java中打印数组

python - 如何找到特定数字的最大索引和最小索引列明智的numpy

c++ - 为 cublasSgemm 使用指向 vector<T>::data() 的指针

c - 将指针字符数组中的值重新分配给该数组中的其他位置?

python - 来自 python,创建数据 block 并通过 SWIG 将其指针传递给 c 程序