Java indexOf method for multiple matches in String

瘦欲@ 提交于 2019-11-27 08:19:08

There is a second variant of the indexOf method, which takes a start-index as a parameter.

i = str.indexOf('x');
while(i >= 0) {
     System.out.println(i);
     i = str.indexOf('x', i+1);
}
Nikita Rybak

There's a another version of indexOf method, taking fromIndex as parameter.
So, you can call it in a loop, each time passing prevPosition + 1 as a second parameter.

Documentation:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf(int, int)

You can specify the start index with indexOf. So, in your loop you store the last position of 'x', then search again using that index + 1.

Here is the solution with Streams API :

String text = "Lets search for E ?";

final char key = "e".charAt(0);
int[] indices = IntStream.range(0, text.length())
    .filter(i -> text.charAt(i) == key)
    .toArray();

Output will be like this :

//1
//6

If you want to add upper case letters into your result, you need to change the filter's argument closure with :

.filter(i -> Character.toLowerCase(text.charAt(i)) == key)

Then the output will be like this :

//1
//6
//16

Additionally if you just want to use the results or print it out for quick testing purposes you can do it with using forEach terminal operation:

IntStream.range(0, text.length())
    .filter(i -> text.charAt(i) == key)
    .forEach(System.out::println);
Alameer Kaiser
String name = "alameer kaiser aziz";
String found = "a";
int num = name.indexOf(found);
while (num >=0) {
    System.out.println(num);
    num = name.indexOf(found,num+1);
}

You want to find multiple characters in a specific string. Yes, you can do that. You can use the overloaded version of indexOf method. Website has descibed all the overloaded version of indexOf methods in detail.https://www.javaians.com/indexof-java/. You can read a detail guide on Java indexOf method.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!