Java String 函数 indexOf() 可以查找多个字符吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39621661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can Java String function indexOf() look for multiple characters?
提问by remington howell
I'm trying to reduce the runtime of a program I'm working on and I want to figure out a simpler way to find the index of a character with an integer value.
我正在尝试减少我正在处理的程序的运行时间,我想找出一种更简单的方法来查找具有整数值的字符的索引。
At the moment, my function traces through each character of a string and returns the indexof the first integer it finds. As an example, if I had the string JohnCena1237728394712
(yes, that's the first string I thought of), the function should return 8 because the first integer that occurs in the string, 1, is at index 8. It must first loop through each character before it to find that index, however, and that gets expensive at times.
目前,我的函数跟踪字符串的每个字符并返回它找到的第一个整数的索引。例如,如果我有字符串JohnCena1237728394712
(是的,这是我想到的第一个字符串),该函数应该返回 8,因为字符串中出现的第一个整数 1 位于索引 8 处。它必须首先遍历每个字符然而,在它之前找到该索引,这有时会变得昂贵。
If it helps when trying to think of an easier way to do this, I can be sure going in to the function that the format of the string will always be "[letters]" + "[numbers]" so I simply have to find the end of the (presumably random) segment of letters to get what I want.
如果在尝试考虑更简单的方法时有帮助,我可以肯定会进入字符串格式始终为“[字母]”+“[数字]”的函数,所以我只需要找到(大概是随机的)字母段的结尾以获得我想要的。
What I would like to do is use indexOf() so I won't have to use a loop, but I do not know a way to use the function without having ten if statements (which, of course, would defeat the purpose).
我想要做的是使用 indexOf() 所以我不必使用循环,但我不知道如何在没有十个 if 语句的情况下使用该函数(当然,这会破坏目的)。
Is there a way to check for multiple integers at once while using indexOf(), or some other function?
有没有办法在使用 indexOf() 或其他一些函数时一次检查多个整数?
采纳答案by slim
You can do this with a regex matcher.
您可以使用正则表达式匹配器执行此操作。
Something like:
就像是:
Pattern pattern = Pattern.compile("\d");
Matcher matcher = pattern.matcher(inputString);
if(matcher.find()) {
return matcher.first();
}
return -1;
This is fairly readable and extensible. Some might consider it overkill compared to a simple for
loop through the string. Compiling the regex takes time, and you have a couple of objects created, and all this costs if you're being fanatical about performance.
这是相当可读和可扩展的。与for
通过字符串的简单循环相比,有些人可能认为它太过分了。编译正则表达式需要时间,并且您创建了几个对象,如果您对性能非常狂热,那么所有这些都需要花费。
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= '0' && c <= '9') {
return i;
}
}
return -1;
Necessary, something will have to look at each character in turn, so there will be a loop somewhere, whether you write it or whether it's in the library method you call.
有必要,有些东西必须依次查看每个字符,所以在某处会有一个循环,不管是你写的还是在你调用的库方法中。
You might be able to squeeze some speed out of multiple cores by breaking the String into chunks and doing something map-reduce-ish. But this would only be worthwhile for really huge strings in which the digits were rare.
您可以通过将 String 分成多个块并执行一些 map-reduce-ish 操作来从多个内核中挤出一些速度。但这仅适用于数字很少的真正巨大的字符串。
回答by Nikolas
The way is to use the Regular Expression, that's a very powerful way to represent the string content..
方法是使用正则表达式,这是一种非常强大的表示字符串内容的方式。
String str = "Hello world";
str.matches("\w+ \w+"); // returns true
And the example of using the classes Pattern
and Matcher
.
以及使用类Pattern
和的示例Matcher
。
String line = "Hello amazing world";
String pattern = "(\w+) \w+ (\w+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println(m.group(1)); // Prints "Hello"
System.out.println(m.group(2)); // Prints "world"
}
回答by XenoRo
You can also avoid .charAt(i)
, although there isn't much point to it... Simply get an array of char
from the string, and loop though that with an indexed FOR
loop that returns the index upon reaching the first digit:
您也可以避免.charAt(i)
,尽管它没有多大意义......只需char
从字符串中获取一个数组,然后使用索引FOR
循环进行循环,该循环在到达第一个数字时返回索引:
char[] chars = string.toCharArray();
for (int i=0; i<chars.lenght; i++) {
if(chars[i] >= '0' && chars[i] <= '9')
return i; //Or whatever code you need.
}
回答by jtwaller
If I'm understanding your question correctly, you have a bunch of characters followed by a bunch of integers.
如果我正确理解你的问题,你有一堆字符后跟一堆整数。
You can use a modified binary searchto find the point in the string where the transition occurs. This should prove useful if you need to analyze very large strings. Worst case performance is O(log n).
您可以使用修改后的二进制搜索来查找字符串中发生转换的点。如果您需要分析非常大的字符串,这应该会很有用。最坏情况下的性能是 O(log n)。
I've coded up an example below:
我在下面编写了一个示例:
public class binSearch {
static int indexFinder(String s) {
// this doesn't check for invalid inputs btw
int beg = 0;
int end = s.length() - 1;
int mid;
int iter = 0;
while (beg < end) {
System.out.println("Iteration: " + iter + " String: " + s.substring(beg, end+1));
mid = (end + beg) / 2;
System.out.println("Mid: " + mid + " char: " + s.charAt(mid));
if (Character.isDigit(s.charAt(mid))) {
if (Character.isDigit(s.charAt(beg))) {
return beg;
}
end = mid;
} else {
beg = mid + 1;
}
iter++;
}
return beg;
}
public static void main(String[] args) {
System.out.println("Running");
String[] strings = {"joohhhnnnnnCEEENNAAAAAA123829898", "efi1029082198"};
for (String s : strings) {
StringBuilder check = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
check.append(i % 10);
}
System.out.println(s);
System.out.println(check.toString() + "\n");
System.out.println("First int index: " + indexFinder(s) + "\n\n");
}
}
}
Output:
输出:
Running
joohhhnnnnnCEEENNAAAAAA123829898
01234567890123456789012345678901
Iteration: 0 String: joohhhnnnnnCEEENNAAAAAA123829898
Mid: 15 char: N
Iteration: 1 String: NAAAAAA123829898
Mid: 23 char: 1
Iteration: 2 String: NAAAAAA1
Mid: 19 char: A
Iteration: 3 String: AAA1
Mid: 21 char: A
Iteration: 4 String: A1
Mid: 22 char: A
First int index: 23
efi1029082198
0123456789012
Iteration: 0 String: efi1029082198
Mid: 6 char: 9
Iteration: 1 String: efi1029
Mid: 3 char: 1
Iteration: 2 String: efi1
Mid: 1 char: f
Iteration: 3 String: i1
Mid: 2 char: i
First int index: 3
回答by CMPS
You can check the ascii of the characters to see if it's an integer or no
您可以检查字符的 ascii 以查看它是否为整数
Note: Assuming the interger is only 1 digit
注意:假设整数只有 1 位
String str = "hello123";
for(int i=0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= '0' && c <= '9') {
// Code goes here
}
}
Alternative solutions:
替代解决方案:
- Use indexOf() for each target character, but this will have a time complexity of O(n^2)
- Store the set of target integers in a set, then loop on the string and check if the characters are in the set (This is good if the integer is more than one digit)
- 对每个目标字符使用 indexOf(),但这将具有 O(n^2) 的时间复杂度
- 将一组目标整数存储在一个集合中,然后在字符串上循环并检查字符是否在集合中(如果整数多于一位,这很好)