Is there a way I can use indexOf in Java to find the position of multiple strings in a given text in a single parse?
开发者_如何学GoFor example, I want to do an indexOf for "you" and "meeting" in one single parse of the text "Will you be able to attend the meeting today?"
Any help will be appreciated! Thanks in advance
As you phrase the question: no.
However you can use a regular expression with matches, string.matches(".*(meeting|today).*"). See the javadoc for the syntax on regular expressions. If you only use letters and number you can construct the pattern from the example, but some characters need quoting with a \, which inside a literal like this would become \.
if you're searching for some patterns in your text then use regular expressions. In your case, i would write a basic function, if you want to locate some strings in a text given:
public static void main(String ... args) {
String a = "i have a little dog";
String [] b = new String [] { "have", "dog" };
locateStrings(a,b);
}
public static int [] locateStrings(String source, String [] str) {
if (source == null || str == null || str.length == 0)
throw new IllegalArgumentException();
int [] result = new int [str.length];
for (int i = 0; i < str.length ; i++) {
result[i] = source.indexOf(str[i]);
}
return result;
}
精彩评论