-2

I Know this quetion has been asked quite few times already but I have a twist.

I have a below string and I wan to check the count how many times given word is repeated in the string.

String randomText = "AbDdfSwapnilswapniljsdncdsbswapnil"

How to count the word "swapnil" is repeated?

Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92

1 Answers1

1

This should work

public static void main(String[] args) {

        String randomText = "AbDdfSwapnilswapniljsdncdsbswapnil";

        String text = "swapnil";
        int times = 0;
        for (int i = 0; i < randomText.length(); i++) {
            if (randomText.substring(i).startsWith(text)) {
                times ++;
            }
        }
        System.out.println(randomText + " contains " + text + " " + times + " times");
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
Countgandi
  • 68
  • 1
  • 7