如何在如此简单的字符串中分别获取整数和字符?
我有这样的字符串: "7d" 、 "5m" 、 "95d" 等。
我需要找到简单的方法来分别获取整数和字符。
我怎样才能做到这一点:
int number = GetNumber("95d"); //should return 95
char code = GetCode("95d"); // should return d
I have strings like: "7d" , "5m" , "95d" etc.
I need to find simple way to be able to get integer and char in the end separately.
How can I achieve this:
int number = GetNumber("95d"); //should return 95
char code = GetCode("95d"); // should return d
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这些是表达式:
EDIT
您实际上只需要创建该
RegExp
对象一次,而不是在每次方法调用时创建。These are the expressions:
EDIT
You really only need to create that
RegExp
object once, not on each method call.RegEx 解决方案的简单替代方案。
您可以将“单独”作为字符串的扩展方法,以使事情变得更清晰。
Simple alternative to the RegEx solutions.
You could make 'Seperate' an extension method on string to make things a bit cleaner.
没有测试,但对我来说,这看起来是实现这一目标的最佳方法。与其他答案相比,它也是提供最大灵活性的方法。
Did not test but to me it looks like the best way to achieve this. It also is the method that provides the most flexibility compared to other answers.
正则表达式可能有点过分了——你已经证明的例子有一个非常简单、一致的格式。尝试以下函数作为起点:
我说“作为起点”是因为您需要考虑边缘情况 - 您将如何处理空字符串?字符串是否可以以多个字母字符结尾,如果是,您将如何处理?希望这些例子能让车轮转动起来。
A regex is probably overkill -- the examples you've proved have a very simple, consistent format. Try the following functions as a starting point:
I say "as a starting point" because you'll need to consider edge cases -- how will you handle empty strings? Can a string end with more than one letter character, and if so, how will you handle this? Hopefully these examples get the wheels turning.
编辑: GetNumber 函数的第二个版本使用“TryParse”而不是“Parse”:
Edit: second version of GetNumber function with 'TryParse' instead of 'Parse':
给你:
另一种稍微简单但相当灵活的方法如下。它会很乐意解析“789xyz”、“1234”或“abcde”等内容。如果没有找到整数前缀,则返回 0。后缀是整数前缀后面的任何内容:如果没有找到后缀,则返回 nil ('')。
Here you go:
Another, slightly more simplistic, but quite flexible approach follows. It will happily parse stuff like '789xyz', '1234' or 'abcde'. If it doesn't find a integer prefix, it returns 0. The suffix is whatever follows the integer prefix: if it doesn't find a suffix, it returns nil ('').
你可以尝试这样的事情:
You can try something like this: