如何检查字符串是否表示正的非零整数?
我不需要知道 int 是什么,我只需要知道它是否是十进制表示中的正非零整数表示,没有前导 0。
它将需要大量记录,因此我希望支票尽可能便宜。
预期的行为是系统永远不应该传递未经验证的内容(因为通常传递的是整数,然后将其转换为字符串进行存储),因此这只是最后的安全检查,以确保没有发生任何奇怪的情况。
I don't need to know WHAT the int is, I just need to know if it is a positive, non-zero integer representation in Decimal representation, with no leading 0's.
It's going to be called for a large number of records, so I'd like it to be as inexpensive a check as possible.
The expected behaviour is that the system should never be passed something that doesn't validate (because it's normally passed ints which it converts to strings for storage) so this is just a final safety check to make sure nothing weird's happened.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然您实际上可以完成将其转换为 int 的过程,但我的假设是您真正想知道的是其中的所有字符是否都是数字?
不幸的是,即使如此,也没有选择,只能线性地运行字符串,尽管这应该比首先转换为整数更快。
使用STL,您可以使用std::find和::isdigit和std::not1
当然您可以只编写一个循环
这不会完全告诉您输入字符串是否代表正数,因为它们可能都是零,并且字符串可能是空的。我们可以轻松地在循环版本中覆盖它。
假设:
必须至少有一个非零
那里)所以 0234 是一个有效的正数
数字
Whilst you could actually go through the process of actually converting it to an int, my assumption is that what you really want to know is whether all the characters in it are digits?
Unfortunately even then there is no option but do linearly run through the string, although this should be faster than converting to an integer first.
Using STL you can use std::find and ::isdigit and std::not1
Of course you could just write a loop
That will not totally tell you if an input string represents a positive number as they might all be zeros, and the string might be empty. We can cover that in the loop version easily.
Assumptions:
must be at least one non-zero in
there) so 0234 is a valid positive
number
检查第一个,循环遍历其余字符,很简单。
Check the first, loop over the rest, easy-peasy.
它确实非常简单,但这取决于要求/允许的输入:
+
?根据上述内容,您可能需要:
+
问题是您还需要验证数字,例如输入
123+456
,如果需要,您可以编写一个简单的状态机来执行上述所有操作。
编辑
如果我理解您的要求,一个子系统会将正整数转换为字符串,这些字符串最终会到达另一个想要验证输入没有发生任何情况的子系统。如果您知道 int 到字符串的转换,那么任务会容易得多:假设没有空格,没有前导零,没有前导
+
,那么您的任务确实像第一个一样“easy-peasy”回答 :)it is indeed quite straightforward, but it depends on the requirements/allowed input:
+
allowed?based on the above, you may need to:
+
the question is also do you need to validate the number, e.g. the input
123+456
you can write a simple state machine that would do all of the above, if needed.
EDIT
if I understand your requirements, one subsystem converts positive ints to strings which are eventually get to another subsystem that wants to validate that nothing happened to the input. if you know your int-to-string conversion, the task is much easier: assuming no whitespace, no leading zeros, no leading
+
, than your task is indeed "easy-peasy" as in the first answer :)