歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言:從字符串中簡單提取數值

C語言:從字符串中簡單提取數值

日期:2017/3/1 10:38:03   编辑:Linux編程

在網絡上看到很多人提到如何用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. if (!isdigit(**s))
  6. {
  7. return -2;
  8. }
  9. while (isdigit(**s))
  10. {
  11. printf("digit found(%c)\r\n", **s);
  12. i = i*10 + *((*s)++) - '0';
  13. }
  14. return i;
  15. }

注:其中isdigit函數是系統ctype.h提供的一個數值檢測函數,類似一個switch case 判斷。

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

測試正常數值字符串結果:


測試字母起始數值字符串結果:


測試字母結束數值字符串結果:

Copyright © Linux教程網 All Rights Reserved