C语言 从 Char* 数组中提取数字(C 字符串)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7892681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract Number from Char* Array (C-String)
提问by darksky
I have a string that occurs in this format:
我有一个以这种格式出现的字符串:
.word 40
.word 40
I would like to extract the integer part. The integer part is always different but the string always starts with .word. I have a tokenizer function which works on everything except for this. When I put .word(.word with a space) as a delimiter it returns null.
我想提取整数部分。整数部分总是不同的,但字符串总是以.word. 我有一个标记器函数,它适用于除此之外的所有内容。当我把.word(.word with a space) 作为分隔符时,它返回 null。
How can I extract the number?
我怎样才能提取数字?
Thanks
谢谢
回答by Alok Save
You can use strtok()to extract the two strings with space as an delimiter.
您可以使用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;
}
Output:
输出:
Splitting string ".Word 40" into tokens:
.Word
40
If you want the number 40as a numeric value rather than a string then you can further use
atoi()to convert it to a numeric value.
如果您希望数字40作为数值而不是字符串,那么您可以进一步使用
atoi()将其转换为数值。
回答by hugomg
回答by andDaviD
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!= 'strncmp(".word ", (your string), 6);
');
This code write in console all digits.
此代码在控制台中写入所有数字。
回答by Akron
Check the string with
检查字符串
int foo;
scanf("%*s %d", &foo);
If this returns 0, then your string starts with ".word " and you can then look at (your string) + 6 to get to the start of the number.
如果返回 0,则您的字符串以“.word”开头,然后您可以查看(您的字符串)+ 6 以到达数字的开头。
回答by Carey Gregory
char* string = ".word 40";
char number[5];
unsigned int length = strlen(string);
strcpy(number, string + length - 2);
The asterisk tells scanf not to store the string it reads. Use fscanf if you're reading from a file, or sscanf if the input is already in a buffer.
星号告诉 scanf 不要存储它读取的字符串。如果您正在读取文件,请使用 fscanf,如果输入已经在缓冲区中,请使用 sscanf。
回答by m0skit0
Quick and dirty:
又快又脏:
##代码##
