integer extraction from string

爷,独闯天下 提交于 2019-12-04 06:39:36

问题


I have an input argument string const char* s I know that it starts the sequence of chars which are integers representation ,this sequence could be of any length ,including 0. After the integer sequence follows sequence of chars which are not integer representation. for example "23meeting","1h". Is there some (builtin) C function which can extract the integer? For example for "23meeting" such operation could be performed :

int x = needed_function("23meeting"); //results x = 23

Thanks


回答1:


atoi() should work fine for this. It should stop at the first non-numeric character.

int x = atoi("23meeting")

EDIT: A comment implies that atoi() is not thread safe or is deprecated from the language. There is some discussion of the thread safety of this function here:

Why does OSX document atoi/atof as not being threadsafe?

Can someone provide a reference to atoi not being thread safe?

And as far as I can tell atoi() is in C99 which is the latest standard (7.20.1.2).




回答2:


You can iterate through the string and can give the condition to get numbers

num=0;
for(i=0;str[i]!='\0';i++) {
if(str[i]>=48 && str[i]<=57)
 num=num*10+(str[i]-48);
  printf("\n%d",num);
} 



回答3:


Try atoi() or the complete strtol():

int x = atoi("23meeting");
int x = (int)strtol("23meeting", (char **)NULL, 10);

Check the man pages on your system (section 3 in Unix).




回答4:


One way would be to use sscanf:

char *str = "23meeting";
unsigned x;
sscanf(str, "%u", &x);
printf("%u\n", x);

For additional error-checking, though, you'll have to do some additional manual checks.




回答5:


atoi() should do what you want to, although a more robust implementation would use strtol().



来源:https://stackoverflow.com/questions/7842153/integer-extraction-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!