2011-10-25 26 views
2

我有發生在這個格式的字符串:提取物數量*陣列(C-字串)

.word 40

我想提取整數部分。整數部分總是不同,但字符串總是以.word開頭。我有一個標記器函數,除了這個之外,它可以用於任何事情。當我把.word(空格爲.word)作爲分隔符時,它返回null。

如何提取數字?

感謝

+0

我認爲這可能是你正在尋找什麼 http://stackoverflow.com/questions/1031872/extract-integer-from-char-buffer –

+0

你應該研究,看看是否有存在的解析器或詞法分析器您感興趣的語言。 –

回答

3

您可以使用sscanf從字符串中提取格式化數據。 (它的工作原理就像scanf函數,而是從一個字符串,而不是從標準輸入讀取數據)

+0

代碼示例很好,因爲它是stackoverflow。 –

8

您可以使用strtok()與空間的分隔符提取兩個字符串。

Online Demo:

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

    int main() 
    { 
     char str[] =".Word 40"; 
     char * pch; 
     printf ("Splitting string \"%s\" into tokens:\n",str); 
     pch = strtok (str," "); 
     while (pch != NULL) 
     { 
      printf ("%s\n",pch); 
      pch = strtok (NULL, " "); 
     } 
     return 0; 
    } 

輸出:

Splitting string ".Word 40" into tokens: 
.Word 
40 

如果你想爲一個數值而不是字符串數40,那麼你還可以使用 atoi()將其轉換爲一個數值。

+0

史詩般的勝利,包括在線演示! – unwind

1

檢查字符串

strncmp(".word ", (your string), 6); 

如果返回0,那麼你的字符串「.word」開頭,然後你可以看看(你的字符串)+ 6中拿到的號碼的開始。

0
int foo; 
scanf("%*s %d", &foo); 

星號告訴scanf不存儲它讀取的字符串。如果您正在讀取文件,請使用fscanf;如果輸入已在緩衝區中,請使用sscanf。

0

快速和骯髒的:在控制檯

char* string = ".word 40"; 
char number[5]; 
unsigned int length = strlen(string); 
strcpy(number, string + length - 2); 
+1

這讓你的字符「40」,但不是一個整數。 –

+0

他沒有指定他想要一個整數。他說:「我想提取整數部分」,但不是以哪種格式。 – m0skit0

1
char str[] = "A=17280, B=-5120. Summa(12150) > 0"; 
char *p = str; 
do 
{ 
if (isdigit(*p) || *p == "-" && isdigit(*(p+1))) 
printf("%ld ", strtol(p,&p,0); 
else 
p++; 
}while(*p!= '\0'); 

這個代碼寫的所有數字。