We help IT Professionals succeed at work.

Analysing Strings ....

luinzi
luinzi asked
on
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??
Comment
Watch Question

Commented:
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;
while((si=src.indexOf(si))!=-1)++num;

should do it.
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.");
     }
}

Author

Commented:
That works fine ...thanks

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