Replace Characters in a String
To replace a character in a string with another character you need to call the method replace() with the two characters as arguments. The first argument is the character to be replaced and the second is the character that will be inserted. |
/** * Main.java * * @author www.javadb.com */ public class Main { /** * This method replaces characters in a string */ public void replaceCharacters() { String str = "aaa bbb ccc"; str = str.replace('b', 'd'); System.out.println(str); } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().replaceCharacters(); } } |
When the code above is executed it will display: |
aaa ddd ccc |
Search for code examples on this site
