开发者

Java indexOf for Multiple strings in one pass

开发者 https://www.devze.com 2023-03-06 10:02 出处:网络
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?

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?

开发者_如何学Go

For 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;      
}
0

精彩评论

暂无评论...
验证码 换一张
取 消