Latest Tutorials| Questions and Answers|Ask Questions?|Site Map

Home Java Beginners Replace Character in String


Share on Google+Share on Google+

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.

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 
  System.out.println("\nYour String after 
repalceing 'h' with 'j'"
  String newString=new String(charArray);
char has been replaced"
  System.out.println("\nThe char not found");

The output of the program is given below:

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.


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 18, 2008

Related Tutorials

Discuss: Replace Character in String   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
June 8, 2011
Reg:Replace Character in String

Hello sir Can u send this code in i'm not able to change some types into style. please Thanking You
August 20, 2012
request for code

can anyone send me java and code to display all classes in jdk and .net...pls mail me