We help IT Professionals succeed at work.

Analysing Strings ....

luinzi asked
Hi there,

I am Analysing a string and I want to see how many times a certain substring (key word) appears, and print it each time it appears within the string, stating its appearance time.

ie. I'm looking for the substring an in the String:


how could I search this string to show an appears 5 times??
Watch Question

The method supplied for such searches is indexOf. It returns an index if the substring is found, -1 if not. So a loop like the following:

String src="qwhhdswranhirgankrtijfanojirhganhifiheran";
int num=0;
int si=0;

should do it.
public class CheckString{
     public static void main(String[] args){
          if (args.length < 2){
               System.out.println("Usage : CheckString string1 string2");

          String s1 = args[0];
          String s2 = args[1];

          int i = -1;
          int n = 0;

          while (!((i = s1.indexOf(s2,i+1)) == -1)){
               System.out.println(s2 + " occurs in " + s1 + " at position " + i);
          System.out.println(n + " occurences.");


That works fine ...thanks

Explore More ContentExplore courses, solutions, and other research materials related to this topic.