我有發生在這個格式的字符串:提取物數量*陣列(C-字串)
.word 40
我想提取整數部分。整數部分總是不同,但字符串總是以.word
開頭。我有一個標記器函數,除了這個之外,它可以用於任何事情。當我把.word
(空格爲.word)作爲分隔符時,它返回null。
如何提取數字?
感謝
我有發生在這個格式的字符串:提取物數量*陣列(C-字串)
.word 40
我想提取整數部分。整數部分總是不同,但字符串總是以.word
開頭。我有一個標記器函數,除了這個之外,它可以用於任何事情。當我把.word
(空格爲.word)作爲分隔符時,它返回null。
如何提取數字?
感謝
您可以使用strtok()與空間的分隔符提取兩個字符串。
#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()將其轉換爲一個數值。
史詩般的勝利,包括在線演示! – unwind
檢查字符串
strncmp(".word ", (your string), 6);
如果返回0,那麼你的字符串「.word」開頭,然後你可以看看(你的字符串)+ 6中拿到的號碼的開始。
int foo;
scanf("%*s %d", &foo);
星號告訴scanf不存儲它讀取的字符串。如果您正在讀取文件,請使用fscanf;如果輸入已在緩衝區中,請使用sscanf。
快速和骯髒的:在控制檯
char* string = ".word 40";
char number[5];
unsigned int length = strlen(string);
strcpy(number, string + length - 2);
這讓你的字符「40」,但不是一個整數。 –
他沒有指定他想要一個整數。他說:「我想提取整數部分」,但不是以哪種格式。 – m0skit0
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');
這個代碼寫的所有數字。
我認爲這可能是你正在尋找什麼 http://stackoverflow.com/questions/1031872/extract-integer-from-char-buffer –
你應該研究,看看是否有存在的解析器或詞法分析器您感興趣的語言。 –