Replace Character in String

This example replaces a character with a specified character in a given string.

Replace Character in String

This example replaces a character with a specified character in a given string.

Replace Character in String

Replace Character in String 

     

This example replaces a character with a specified character in a given string.

To replace a character with the given character in sting first convert the string into char array. Use getChars(int scrStart, int scrEnd, char[] destChar, int destStart) method for converting a string into an array of characters. Then use while loop for comparing the "oldChar" ( character name for replace) to be change with the new character of the array. If any match find then replace the "oldChar" with newChar (character name to replace) and set flag =1. To convert charArray into string, pass "charArray" into String class.

getChars(int scrStart, int scrEnd, char[] destChar, int destStart): This method returns an array of characters from a string. We are passing four parameter into this method. First parameter scrStart is the starting point while second parameter scrEnd is the end point of the source string to convert the string into a char array. The destChar is the destined array which stores all the characters. The destStart  is starting index to store the characters. 

 The code of the program is given below:

public class Replace{
  public static void main(String s[]){
  String string="rajesh raju raja rahul ray rani ram";
  char  oldChar='r';
  char newChar='g';
  int numChar=string.length();
  char[] charArray=new char[numChar];
  string.getChars(0, numChar, charArray,0);
  int i=0,flag=0;  
  System.out.println("Your String before 
repalce\n"
+string);
  while(i<charArray.length)
  {
  if(charArray[i]==oldChar)
  {
  charArray[i]=newChar;
  flag=1;
  }
  i++;
  }
  if(flag==1)
  {
  System.out.println("\nYour String after 
repalceing 'h' with 'j'"
);
  String newString=new String(charArray);
  System.out.println(newString+"\n\nYour 
char has been replaced"
);
  }
  if(flag==0)
  {
  System.out.println("\nThe char not found");
  }  
  }
}

The output of the program is given below:

C:\replace>javac Replace.java
C:\replace>java Replace
Your String before repalce
rajesh raju raja rahul ray rani ram
Your String after repalceing 'h' with 'j'
gajesh gaju gaja gahul gay gani gam
Your char has been replaced

Download this example.