java replace character in string code example

Example 1: how to change single character of a string in java

//short answer: you cannot individually change any specific character
//of a String in java. You can however do this:

String s1 = "This is a String";
String s2 = s1.substring(0, 8) + "o" + s1.substring(9);
System.out.println(s2);
//Prints "This is o String", replaced the 8th character with an o

Example 2: java replace character

// We want to replace every # with a 8
String larry = "Larry is # years old";
String newString = larry.replace("#", "8");

Example 3: java replace character in string

String s = "new String";
String replaced = s.replace("new","Test");
							  ^		 ^
                             old    new char

Example 4: java string replace character at position

String str = in.nextLine();	//Original String
char cr = in.next().charAt(0); // character to replace
int index = in.nextInt();	// Index where replaced
str = str.substring(0, index) + cr + str.substring(index + 1);// modified string

Example 5: replace character in string java

String str = ".............................."; 

        int index = 5; 
  
        char ch = '|'; 
 
        StringBuilder string = new StringBuilder(str); 
        string.setCharAt(index, ch); 

        System.out.println(string);

Example 6: how to replace a character with another character in a string in java

public class JavaExample{
   public static void main(String args[]){
	String str = new String("Site is BeginnersBook.com");

	System.out.print("String after replacing com with net :" );
	System.out.println(str.replaceFirst("com", "net"));

	System.out.print("String after replacing Site name:" );
	System.out.println(str.replaceFirst("Beginners(.*)", "XYZ.com"));
   }
}

Tags:

Java Example