我的应用程序中有一个(大)字符串文件,其中包含一系列随机字符a-Z和0-9,但也包含";“、"/”、"?“、":”和"@“。我希望我的应用程序告诉我6位数字连续显示的最近位置(如"105487“或"558463")。
实现这一目标的最佳方法是什么?感谢您对此进行调查。
发布于 2012-10-02 05:25:13
一种有效的方法是迭代字符串的字符,并测试每个字符是否为数字。找到匹配项后,继续查找序列的其余部分。就像这样
int nDigits=0, i = 0;
CharacterIterator it = new StringCharacterIterator("very long string123456");
for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
i++;
nDigits = (ch.isDigit() ? nDigits++ : 0);
if (nDigits == 5) {
// DONE. Position is "i"
}
}发布于 2012-10-02 05:28:21
您可以使用正则表达式。
String regex = "(\\d{6})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(YOU STRING HERE);
// Check all occurrences
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
System.out.println(" Found: " + matcher.group());
}这样就可以完成任务了。
(来自here的代码示例)
发布于 2012-10-02 05:24:14
在迭代字符串的字符时使用Character.isDigit,然后向上计数一个数字,直到找到6个连续的数字,如果序列中断,则重置该数字。跟踪索引,您可以简单地通过减法计算最近的位置。
这不是很有效,但我认为如果字符串不太大,O(n)就足够了。对于优化,请看Luiggi Mendoza在评论中提出的建议。
https://stackoverflow.com/questions/12681275
复制相似问题