C语言:从字符串中简单提取数值


在网络上看到很多人提到如何用C语言获取字符串中的数值的问题。其实这个问题的解决方法很多,这里给出一段简单的分析字符串,提取数值的代码:

从字符串中简单提取数值,其主要功能有:

1)扫描字符串中一段数值字符串;

2)扫描一段连续数值字符,并按十进制格式提取数值;

3)如果字符串第一个字符非数值字符,直接停止,报错;

4)数值字符段后有非数值字符,直接停止读取后续字符,将提取的字符以十进制格式转换输出;

其主要实现部分,见skip_atoi代码

 
  1. int skip_atoi(char **s)  
  2. {  
  3.     int i = 0;  
  4.     printf("scan string %s, char 0x%x, num = 0x%x, i = %d\r\n", *s, **s, **s - '0', i);  
  5.       
  6.     if (!isdigit(**s))  
  7.     {  
  8.         return -2;  
  9.     }  
  10.       
  11.     while (isdigit(**s))  
  12.     {  
  13.         printf("digit found(%c)\r\n", **s);  
  14.         i = i*10 + *((*s)++) - '0';  
  15.     }  
  16.     return i;  
  17. }

注:其中isdigit函数是系统ctype.h提供的一个数值检测函数,类似一个switch case 判断。

 
  1. isdigit()  
  2.        checks for a digit (0 through 9).  

 测试正常数值字符串结果:


测试字母起始数值字符串结果:


测试字母结束数值字符串结果:

相关内容