检查 C++ 中字符串以什么数字结尾
在 C++ MD2 文件加载器中,我有很多框架,每个框架都有一个以数字结尾的名称,例如
- 。
- stand0stand1stand2stand3stand4
- 如何
- 内容
- 包含
- 我
- stand10stand11run0run1run2
- 的
- 字符串
- 等
- ...
获取
不 后面的数字? 例如,将“stand10”更改为“stand”的函数
In a C++ MD2 file loader, I have a lot of frames, each with a name that ends with a number, such as
- stand0
- stand1
- stand2
- stand3
- stand4
- ...
- stand10
- stand11
- run0
- run1
- run2
etc.
How do I get what the string is without the number behind? e.g. a function that changed "stand10" to just "stand"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
字符串::find_last_not_of(“0123456789”)
进而
string::substr()
为您提供最后一个非数字/数字的位置。 只需取前面的所有字符即可,这就是基本名称。
加一以获取字符串末尾的数字序列的开头。
注意:没有错误检查或其他测试。
编辑
当您的“基本名称”末尾有数字时,所有解决方案都会出现问题。
例如,如果基本字符串是“base1”,那么您永远无法获得正确的基本名称。 我想你已经意识到了这一点。
或者我错过了什么? 只要基本名称不能在后缀数字之前有数字,它就可以正常工作。
string::find_last_not_of("0123456789")
and then
string::substr()
that gives you the position of the last non digit/number. Just take all the preceding characters and that is the base name.
Increment by one to get the start of the number sequence at the end of the string.
Note: no error checking or other tests.
EDIT
there is a problem with ALL the solutions when your "base name" has a number at the end.
for example, if the base string is "base1" then you can never get the proper base name. I assume you already are aware of this.
Or am I missing something? As long as the base name can't have a number at the end just before the postfix number it will work fine.
只是为了展示另一种方式,反向迭代器:
如果你有 boost::bind,你可以让你的生活更轻松
Just to show another way, reverse iterators:
If you have boost::bind, you can make your life easier
为了完成它,用 find_first_of:
just one line :)
另外,对于这些事情,我喜欢使用正则表达式(尽管这种情况很简单):
Just to complete it, one with find_first_of:
just one line :)
Also, for these things, I like to use regular expressions (althought this case is very simple):
C 风格的实现方法:
从左侧开始逐个字符地遍历字符串。 当您读取一个数字时,停止并将其标记为字符串的末尾。
C-style way of doing it:
Iterate through your string character-by-character, starting from the left. When you read a number, stop, and mark it as the end of your string.
又快又脏,而且不太优雅:
Quick and dirty and not too elegant: