This example replaces a character with a specified character in a given string.This example replaces a character with a specified character in a given 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:
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