Java String example to replace a character with new character using replace


public String replace(char oldChar,char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a String object is returned that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

Examples:
 "mesquite in your cellar".replace('e', 'o')
         returns "mosquito in your collar"
 "the war of baronets".replace('r', 'y')
         returns "the way of bayonets"
 "sparring with a purple porpoise".replace('p', 't')
         returns "starring with a turtle tortoise"
 "JonL".replace('q', 'x') returns "JonL" (no change)
 
Program:
package com.candidjava;

public class StringReplace 
{
     public static void main(String args[]) 
    { 
      String s1="String Handling Functions";
      System.out.println("String:"+s1+"\n");
 
      String s2=s1.replace('i','l'); 
      System.out.println("Replaced String is:"+s2);
     } 
}

Output:
                   String:String Handling Functions
                   Replaced String is:Strlng Handllng Functlons

Description:
In the above program, the specified character i placed number of times in the given string. l is a new character that replace all the character i in the string.

Parameters:
oldChar - the old character.
newChar - the new character.

Returns:
a string derived from this string by replacing every occurrence of oldChar with newChar.


Related Post

Comments

JAYAPRIYA
         output is wrongly entered; String:String Handling Functions Replaced String is:Strlng Handllng Functlons
K.Lakshminarayana
         WAJP to extract every character of the word in the given string
Mathan
         Output corrected
K.Lakshminarayana
         Write a program to print 1to10 without using loops

©candidjava.com