如何提取字符串中的数字在C? [英] How to extract numbers from string in c?

查看:113
本文介绍了如何提取字符串中的数字在C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有像 ab234cid *(S349 *(20KD 一个字符串,我想提取所有的数字 234,349,20 ,我该怎么办?

Say I have a string like ab234cid*(s349*(20kd and I want to extract all the numbers 234, 349, 20, what should I do ?

推荐答案

您可以用的 与strtol ,像这样的:

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if (isdigit(*p)) { // Upon finding a digit, ...
        long val = strtol(p, &p, 10); // Read a number, ...
        printf("%ld\n", val); // and print it.
    } else { // Otherwise, move on to the next character.
        p++;
    }
}

链接 ideone

这篇关于如何提取字符串中的数字在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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