C语言 如何从c中的字符串中提取数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13399594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:26:09  来源:igfitidea点击:

How to extract numbers from string in c?

cstring

提问by CDT

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

假设我有一个像这样的字符串ab234cid*(s349*(20kd,我想提取所有数字234, 349, 20,我该怎么办?

回答by dasblinkenlight

You can do it with strtol, like this:

你可以这样做strtol,像这样:

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

Link to ideone.

链接到ideone

回答by hmjd

A possible solution using sscanf()and scan sets:

使用sscanf()和扫描集的可能解决方案:

const char* s = "ab234cid*(s349*(20kd";
int i1, i2, i3;
if (3 == sscanf(s,
                "%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
                &i1,
                &i2,
                &i3))
{
    printf("%d %d %d\n", i1, i2, i3);
}

where %*[^0123456789]means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW.

其中%*[^0123456789]意味着忽略输入,直到找到一个数字。请参阅http://ideone.com/2hB4UW 上的演示。

Or, if the number of numbers is unknown you can use %nspecifier to record the last position read in the buffer:

或者,如果数字的数量未知,您可以使用%n说明符记录在缓冲区中读取的最后一个位置:

const char* s = "ab234cid*(s349*(20kd";
int total_n = 0;
int n;
int i;
while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
{
    total_n += n;
    printf("%d\n", i);
}

回答by MOHAMED

here after a simple solution using sscanf:

在使用sscanf以下简单解决方案之后:

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

char str[256]="ab234cid*(s349*(20kd";
char tmp[256];

int main()
{

    int x;
    tmp[0]='
char tmp[256];

for(i=0;str[i];i++)
{
  j=0;
  while(str[i]>='0' && str[i]<='9')
  {
     tmp[j]=str[i];
     i++;
     j++;
  }
  tmp[j]=0;
  printf("%ld", strtol(tmp, &tmp, 10));
  // Or store in an integer array
'; while (sscanf(str,"%[^0123456789]%s",tmp,str)>1||sscanf(str,"%d%s",&x,str)) { if (tmp[0]=='
// Provided 'c' is only a numeric character
int parseInt (char c) {
    return c - '0';
}
') { printf("%d\r\n",x); } tmp[0]='
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
char *str ="ab234cid*(s349*(20kd", *ptr = str;
while (*ptr) { // While there are more characters to process...
    if ( isdigit(*ptr) ) {
        // Found a number
        int val = (int)strtol(ptr,&ptr, 10); // Read number
        printf("%d\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        ptr++;
    }
}

}
'; } }

回答by Aki Suihkonen

Make a state machine that operates on one basic principle: is the current character a number.

制作一个基于一个基本原则运行的状态机:当前字符是一个数字。

  • When transitioning from non-digit to digit, you initialize your current_number := number.
  • when transitioning from digit to digit, you "shift" the new digit in:
    current_number := current_number * 10 + number;
  • when transitioning from digit to non-digit, you output the current_number
  • when from non-digit to non-digit, you do nothing.
  • 当从非数字转换为数字时,您初始化 current_number := number。
  • 从数字转换到数字时,您将新数字“移动”为:
    current_number := current_number * 10 + number;
  • 当从数字转换为非数字时,您输出 current_number
  • 当从非数字到非数字时,你什么都不做。

Optimizations are possible.

优化是可能的。

回答by P.P

If the numbers are seprated by whitespace in the string then you can use sscanf(). Since, it's not the case with your example, you have to do it yourself:

如果数字由字符串中的空格分隔,那么您可以使用 sscanf()。因为,你的例子不是这种情况,你必须自己做:

##代码##

}

}

回答by Divyanshu Kushwaha

Or you can make a simple function like this:

或者你可以做一个像这样的简单函数:

##代码##

回答by Felix

##代码##