Pages

Friday, August 31, 2012

how to print a word after a word in java

public class SearchString{
   public static void main(String[] args) {
      String strOrig = "how to print a word after a word in java.";
      String word=null;
      int intIndex = strOrig.indexOf("print");
      if(intIndex == - 1){
         System.out.println("the word not found");
      }else{
      String substring1 = strOrig.substring(intIndex );
      String substring2 = substring1.substring(substring1.indexOf(" "));
      substring2 = substring2.trim();
      word = substring2.substring(0, substring2.indexOf(" "));
        
         System.out.println(word);
      }
   }
}

Output
 it will print 'a' as it is the word after print...


Explanation of code
int intIndex = strOrig.indexOf("print");
this code segment used to  find the word is occurred or not

String substring1 = strOrig.substring(intIndex );
this code segment create a sub-string from the word 'print' to the end of the original string.

String substring2 = substring1.substring(substring1.indexOf(" "));
this will create sub-string from the next space till end (will remvoe the word 'print form the sub string)

substring2 = substring2.trim();
trim the string (remove the first and last spaces...)

word = substring2.substring(0, substring2.indexOf(" "));

taking our required sub string