1

I have a string, so how could I check how many times a specific substring is found in the string?

For example,

String1 = "The fox and the hound"

, and I want to know how many times the word "the" appeared.

The idea I had was since "the" has length three, I could check every set of three characters in the string, but I am hoping there is a more efficient way.

1
  • 5
    refer to indexOf(String) and indexOf(String, int) in API doc Commented Jan 21, 2015 at 23:58

2 Answers 2

3

You can use StringUtils to count like so:

String string = "The fox and the hound".toLowerCase(); // to lower

int count = StringUtils.countMatches(string, "the"); // count is 2
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a solution with regular expression:

import java.util.regex.*;

public class RegexToCountWords {
  public static final String SAMPLE_STRING = "The fox and the hound";
  public static final String SEARCH_STRING = "the";

  public static void main(String[] args) {
    // pattern to compare \\b matches word boundaries
    Pattern pattern = Pattern.compile("\\b" + SEARCH_STRING + "\\b");
    Matcher matcher = pattern.matcher(SAMPLE_STRING.toLowerCase());
    //matcher.find() checks for all occurrances
    int count = 0;
    while (matcher.find()) {
      count++;
    }
    System.out.println("Sample String : " + SAMPLE_STRING);
    System.out.println("Number of matching strings : " + count);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.