Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java String Replace Example

  1. /*
  2. Java String replace example.
  3. This Java String Replace example describes how replace method of java String
  4. class can be used to replace character or substring by new one.
  5. */
  6.  
  7. public class JavaStringReplaceExample{
  8.    
  9.     public static void main(String args[]){
  10.        
  11.         /*
  12.         Java String class defines three methods to replace character or
  13.         substring from the given Java String object.
  14.        
  15.         1) String replace(int oldChar, int newChar)        
  16.         This method replaces a specified character with new character
  17.         and returns a new string object.
  18.        
  19.         2) String replaceFirst(String regularExpression, String newString)        
  20.         Replaces the first substring of this string that matches the
  21.         given regular expression with the given new string.
  22.        
  23.         3) String replaceAll(String regex, String replacement)        
  24.         Replaces the each substring of this string that matches the
  25.         given regular expression with the given new string.
  26.         */
  27.        
  28.         String str="Replace Region";
  29.        
  30.         /*
  31.         Replaces all occurrences of given character with new one
  32.         and returns new String object.
  33.         */
  34.        
  35.         System.out.println(str.replace( 'R','A' ));
  36.        
  37.         /*
  38.         Replaces only first occurrences of given String with new one
  39.         and returns new String object.
  40.         */
  41.        
  42.         System.out.println(str.replaceFirst("Re", "Ra"));
  43.        
  44.         /*
  45.         Replaces all occurrences of given String with new one and
  46.         returns new String object.
  47.         */
  48.        
  49.         System.out.println(str.replaceAll("Re", "Ra"));
  50.        
  51.     }
  52.  
  53. }
  54.  
  55. /*
  56. OUTPUT of the above given Java String Replace Example would be:
  57. Aeplace Aegion
  58. Raplace Region
  59. Raplace Ragion
  60. */
Your rating: None Average: 3.9 (10 votes)
Share this