How can I check if a specific string occurs multiple times in an other string?

My code takes input from user and if there are two "bread" substrings, the string between them is printed. For example, "breadjavabread" outputs "java". However, when my code only has one "bread" string, an error pops up. For example, "usjdbbreaddudub". How can I resolve this?

String cheese = "no bread";
String bread = "bread";
for (int i = 0; i < s.length() - 5; i++)
{
  String m = s.substring(i, i + 5);
  if (m.equals(bread))
  {
    cheese = s.substring(s.indexOf(bread) + bread.length(), s.lastIndexOf(bread));
  }
}

System.out.print(cheese);

1 answer

  • answered 2019-04-15 07:05 Sweeper

    There are many ways you can solve this problem. Here are 3 of them

    1. Comparing indexOf and lastIndexOf

      String cheese;
      String bread = "bread";
      int firstIndex = s.indexOf(bread);
      int lastIndex = s.lastIndexOf(bread);
      if (firstIndex == -1) {
          cheese = "no bread";
      } else if (lastIndex == firstIndex) {
          cheese = "only one bread";
      }
      cheese = s.substring(firstIndex + bread.length(), lastIndex);
      
      System.out.print(cheese);
      
    2. Regular expressions:

      Matcher m = Pattern.compile("bread(.+?)bread").matcher(s);
      if (m.find()) {
          System.out.println(m.group(1));
      } else {
          System.out.println("Not enough bread");
      }
      
    3. Split:

      String[] parts = s.split("bread");
      if (parts.length == 3) {
          System.out.println(parts[1]);
      } else {
          System.out.println("Not enough or too much bread");
      }