replaceFirst() String Example

November 18, 2014 | class String
After seeing replace() method in String, let us study another similar method replaceFirst() String.
What Java API says about the method:
  • String replaceFirst (String str, String replaceString): Replaces the first occurrence of str in the original string(calling string) with replaceString, The original string is not getting disturbed, but the returned string gets effected. See example.

Following is the example.

public class Demo
  public static void main(String args[])
   String str1 = "hello hello hello hello";	

   System.out.println("Original string str1 before replaceFirst() is called: " + str1);  
   String str2 = str1.replaceFirst("hello", "world");            // see usage of replaceFirst() String
   System.out.println("Original string str1 after replaceFirst() is called: " + str1);
   System.out.println("Returned string str2 after replaceFirst() is called: " + str2);

replaceFirst() String Output screenshot on replaceFirst() String Example

Also refer for a similar method replace().

Pass your comments and suggestions on this tutorial "replaceFirst() String Example".