Java indexOf method for multiple matches in String

前端 未结 6 1425
走了就别回头了
走了就别回头了 2020-11-29 06:24

I had a question about the indexOf method. I want to find multiple cases of \"X\" in a string.

Suppose my string is \"x is x is x is x\", I want to find x in all of

6条回答
  •  一整个雨季
    2020-11-29 07:06

    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);
    

提交回复
热议问题