Count no.of times a word repeats in String in Java

An example to calculate the no.of times a word repeats in a string in Java with a simple logic.

Example



// Import for Scanner
import java.util.*;

class CountRepeat
{

public static void main(String args[])
{

// Create Scanner object
Scanner s=new Scanner(System.in);

// Read a string from the user and store it in st
String st=s.nextLine();

// Read the find string, for which the density should be calculated
String find=s.nextLine();

// Let the count of occurence of 'find' in 'st' be 0 initially
int count=0;

// Let the index be 0, [not necessary to be so..]
int k=0;

// Loop till end of main string 'st'
for(int i=0;i<st.length();i++)
{

// Considering case (i.e. case sensitive)
//k=st.indexOf(find,k+find.length());

// Ignoring case (i.e. non case sensitive)
k=st.toLowerCase().indexOf(find.toLowerCase(),k+find.length());

// Print the index if you wish to..
System.out.println(k);

// If find string is not found (-1 is returned) again, then go out of the loop i.e. jumps to System.out.println() [See down]
if(k==-1) break; else count++;

}

System.out.println("The string occurred "+count+" times");

}

}

Output


gowtham Gutha gutha
gutha
8
14
-1
The string occurred 2 times


Ignoring case:  Here, both the find string and st (main string) are converted into lower case and stored in another object temporarily (here, no name is given to those objects).So it is obvious that the original strings 'find' and 'st' are not modified since the operations are performed on another temporary String object.

Also see Count no.of alphabets in a String in Java and Count no.of digits in a String in Java

No comments: