从字符串C中提取数字

时间:2017-07-18 15:50:26

标签: c string

我有一堆类似这样的字符串。 我想提取它们,将它们放入数组或int。

例如:

  • DATA:PHONENUMBER123456AGE7890
  • TEL:123
  • TEL1A:123456
  • TEL2B:123456

我需要提取:

DATA PHONENUMBER 123456 AGE 7890
TEL 123
TEL1A 123456
TEL2B 123456

并使用printf输出这些值

a=DATA b=PHONENUMBER c=123456 d=AGE e=7890
a=TEL b=123
a=TEL1A b=123456
a=TEL2B b=123456

我使用了以下代码,但这不合适。 这适用于123abc但是如果输入是abc123,我该如何处理字母然后处理数字。

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


int main(void)
{
  char buf[BUFSIZ];
  char *p;
  long int i;

  printf ("Enter a number: ");

  if (fgets(buf, sizeof(buf), stdin) != NULL)
  {
    i = strtol(buf, &p, 10);

    if (buf[0] != '\n' && (*p == '\n' || *p == '\0'))
      printf ("Valid number of %ld entered\n", i); 
    else  printf ("The number was %d, followed by %s\n", i, p);
  }  

  return(0);
}

/*
 * Program output:
   Enter a number: 123abc
   The number was 123, followed by abc
 *
 */

我试图提取它们,但我真的无法写出来。 该程序使用C.

提前感谢您的支持!

1 个答案:

答案 0 :(得分:1)

使用sscanf和scansets可以提取子字符串。扫描集%79[^:]最多可扫描79个不是:的字符,而%79[0-9]最多可扫描79个数字字符。 %n说明符将捕获扫描处理的字符数。这允许子扫描从上次扫描停止的位置开始。

#include <stdio.h>

int main ( void) {
    char a[80] = "";
    int c = 0;
    int result = 0;
    int each = 0;
    int span = 0;
    int offset = 0;
    char text[][80] = {
        "DATA:PHONENUMBER123456AGE7890"
        , "TEL:123"
        , "TEL1A:123456"
        , "TEL2B:123456"
    };

    while ( 1 == sscanf ( text[each], " %79[^:]:%n", a, &span)) {//scan up to : then scan :
        printf ( "\n%s\n", text[each]);//print full element of text array
        offset = span;
        printf ( "text before : = %s\n", a);
        do {
            if ( 1 == ( result = sscanf ( text[each] + offset, " %79[^0-9]%n", a, &span))) {// scan non-numbers
                offset += span;
                printf ( "\ttext = %s\n", a);
            }
            if ( 1 == ( result = sscanf ( text[each] + offset, " %79[0-9]%n", a, &span))) {//scan numbers
                offset += span;
                printf ( "\tnumber text = %s\n", a);
                if ( 1 == sscanf ( a, "%d", &c)) {//scan text number to int
                    printf ( "\tnumber value = %d\n", c);
                }
            }
        } while ( result != EOF);//loop until end of text[each]
        each++;//next element in text array
        if ( each >= 4) {
            break;
        }
    }
    return 0;
}