Sunday, January 26, 2014

How to replace a substring inside a string?

Source:
public class ReplaceSubString {
   public static void main(String args[]){
      String str="abcdefghijklmnopqrstuvwxyz";
      System.out.println( str );
      System.out.println( str.replace( 'q','Q' ) );
      System.out.println( str.replace( "abc","ABC" ) );
      System.out.println( str.replaceFirst("jkl", "-K-") );
      System.out.println( str.replaceAll("lmno", "XXXX") );
   }
}

Output:
   $ java ReplaceSubString 
   abcdefghijklmnopqrstuvwxyz
   abcdefghijklmnopQrstuvwxyz
   ABCdefghijklmnopqrstuvwxyz
   abcdefghi-K-mnopqrstuvwxyz
   abcdefghijkXXXXpqrstuvwxyz

Blog Archive