遍历字符串?
不完全确定这是可能的,但假设我有两个像这样的字符串:
"IAmAString-00001"
"IAmAString-00023"
通过向上移动末尾数字的索引,从 IAmAString-0001 迭代到 IAmAString-00023 的快速简便方法是什么?
问题比这更普遍一些,例如,我可以处理的字符串可以是任何格式,但最后一堆字符始终是数字,因此像 Super_Confusing-String#w00t0003 这样的东西,在这种情况下,最后一个 0003 将是是我用来迭代的东西。
有什么想法吗?
Not entirely sure this is possible, but say I have two strings like so:
"IAmAString-00001"
"IAmAString-00023"
What would be a quick'n'easy way to iterate from IAmAString-0001 to IAmAString-00023 by moving up the index of just the numbers on the end?
The problem is a bit more general than that, for example the string I could be dealing could be of any format but the last bunch of chars will always be numbers, so something like Super_Confusing-String#w00t0003 and in that case the last 0003 would be what I'd use to iterate through.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以使用 char.IsDigit:
生成以下输出:
You can use
char.IsDigit
:which produces this output:
string.Format 和 for 循环应该做你想要的。
或类似的东西(不在编译器前面)。
string.Format and a for loop should do what you want.
or something close to that (not sitting in front of a compiler).
您可以使用正则表达式:
要更具体地回答,您可以使用命名组来提取您需要的内容:
You could use a Regex:
To answer more specifically, you could use named groups to extract what you need:
如果您可以假设最后 5 个字符是数字,则:
If you can assume that the last 5 characters are the number then:
该函数将找到尾随号码。
假设所有基本字符串都相同,这将在字符串之间进行迭代。
This function will find the trailing number.
Assuming all your base strings are the same, this would iterate between strings.
我认为如果你从最后一次开始搜索会更好(里克已经给你投票了,因为这是你的逻辑:-))
HTH
I think it would be better if you do the search from the last (Rick already upvoted you since it was ur logic :-))
HTH
如果最后 X 个数字始终是数字,那么:
如果最后一个数字的长度可以是 3、4 或 5,那么您将需要更多的逻辑:
我不擅长复杂的正则表达式。正因为如此,当不需要最大程度的优化时,我总是回避它。原因是 RegEx 并不总是按照您期望的方式解析字符串。如果有替代解决方案仍然可以快速运行,那么我宁愿走这条路,因为我更容易理解并知道它可以与任何字符串组合一起使用。
例如:如果您使用此处提供的一些其他解决方案以及“I2AmAString-000001”等字符串,那么您将得到“2000001”作为您的数字,而不是“1”。
If the last X numbers are always digits, then:
If the last digits can be 3, 4, or 5 in length, then you will need a little more logic:
I'm not good with complicated RegEx. Because of this, I always shy away from it when maximum optimization is unnecessary. The reason for this is RegEx doesn't always parse strings the way you expect it to. If there is and alternate solution that will still run fast then I'd rather go that route as it's easier for me to understand and know that it will work with any combination of strings.
For Example: if you use some of the other solutions presented here with a string like "I2AmAString-000001", then you will get "2000001" as your number instead of "1".