-5

Say I had a string

String s = "foofoo bar barbarbar foo

and I wanted to find all the occurrences of foo and print them out like so:

foo foo foo

I've already looked into StringUtils, but it seems to me (an amateur) that this library is only able to count the number of occurrences of foo. Is there something I'm doing wrong here? Or is regex really the best way to go?

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
brownac
  • 61
  • 2
  • 7

1 Answers1

-1

You can use indexOf method of String class and substring method of the same class to achieve the desired result, but using regex it would be less typing and easier to implement. I have provided a possible solution for you below

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Sample {
public static void main(String[] args) {
    String s = "foofoo bar barbarbar foo";

    Pattern p = Pattern.compile("foo");
    Matcher m = p.matcher(s);
    while(m.find()){
        System.out.print(m.group() + " ");
    }
}
}