Link to home
Start Free TrialLog in
Avatar of luinzi
luinzi

asked on

Analysing Strings ....

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:

"qwhhdswranhirgankrtijfanojirhganhifiheran"

how could I search this string to show an appears 5 times??
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
public class CheckString{
     public static void main(String[] args){
          if (args.length < 2){
               System.out.println("Usage : CheckString string1 string2");
               System.exit(0);
          }

          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);
               n++;
          }
          System.out.println(n + " occurences.");
     }
}
Avatar of luinzi
luinzi

ASKER

That works fine ...thanks