我有一个以这种格式出现的字符串:
.word 40
我想提取整数部分.整数部分始终不同,但字符串始终以.word.我有一个tokenizer函数,它可以处理除此之外的所有内容.当我将.word(.word with a space)作为分隔符时,它返回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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Splitting string ".Word 40" into tokens:
.Word
40
Run Code Online (Sandbox Code Playgroud)
如果您想将数字40作为数字值而不是字符串,那么您可以进一步使用
atoi()将其转换为数字值.