试图从C中的字符串中删除所有数字 [英] Trying to remove all numbers from a string in C

查看:52
本文介绍了试图从C中的字符串中删除所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串(char *)中取出所有数字...

I'm trying to take all of the numbers out of a string (char*)...

这就是我现在拥有的:

    // Take numbers out of username if they exist - don't care about these
    char * newStr;
    strtoul(user, &newStr, 10);
    user = newStr;

我的理解是strtoul应该将字符串转换为无符号的long.非数字字符将放入传入的指针(第二个arg)中.当我将用户重新分配给newStr并进行打印时,字符串保持不变.为什么是这样?有人知道更好的方法吗?

My understanding is that strtoul is supposed to convert a string to an unsigned long. The characters that are not numbers are put into the passed in pointer (the 2nd arg). When i reassign user to newStr and print it, the string remains unchanged. Why is this? Does anyone know of a better method?

从文档示例中:

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

int main()
{
char str[30] = "2030300 This is test";
char *ptr;
long ret;

ret = strtoul(str, &ptr, 10);
printf("The number(unsigned long integer) is %lu\n", ret);
printf("String part is |%s|", ptr);

return(0);
}

让我们编译并运行以上程序,这将产生以下结果:

Let us compile and run the above program, this will produce the following result:

The number(unsigned long integer) is 2030300
String part is | This is test|

推荐答案

char* RemoveDigits(char* input)
{
    char* dest = input;
    char* src = input;

    while(*src)
    {
        if (isdigit(*src)) { src++; continue; }
        *dest++ = *src++;
    }
    *dest = '\0';
    return input;
}

测试:

int main(void)
{
    char inText[] = "123 Mickey 456";
    printf("The result is %s\n", RemoveDigits(inText));
    // Expected Output: " Mickey "
}

数字已删除.

这篇关于试图从C中的字符串中删除所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆