从字符串中提取整数
我有一个输入参数字符串 const char* s
我知道它启动了整数表示的字符序列,该序列可以是任意长度,包括 0。 在整数序列之后是不是整数表示的字符序列。 例如“23meeting”,“1h”
。 是否有一些(内置)C 函数可以提取整数? 例如,对于“23meeting”,可以执行此类操作:
int x = needed_function("23meeting"); //results x = 23
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以迭代字符串并给出获取数字的条件
You can iterate through the string and can give the condition to get numbers
atoi() 应该可以正常工作。它应该停在第一个非数字字符处。
编辑:注释暗示 atoi() 不是线程安全的或已从语言中弃用。这里有一些关于该函数的线程安全性的讨论:
为什么 OSX 将 atoi/atof 记录为不是线程安全的?
有人可以提供 atoi 不是线程安全的参考吗?
据我所知 atoi() 位于 C99 中,这是最新的标准(7.20.1.2)。
atoi() should work fine for this. It should stop at the first non-numeric character.
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).
尝试
atoi()
或完整的strtol()
:检查系统上的手册页(Unix 中的第 3 节)。
Try
atoi()
or the completestrtol()
:Check the man pages on your system (section 3 in Unix).
一种方法是使用 sscanf:
不过,为了进行额外的错误检查,您必须执行一些额外的手动检查。
One way would be to use
sscanf
:For additional error-checking, though, you'll have to do some additional manual checks.
atoi()
应该做你想做的尽管更强大的实现将使用strtol()
。atoi()
should do what you want to, although a more robust implementation would usestrtol()
.