java change string character code example

Example 1: java replace character

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

Example 2: 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 3: java replace character in string

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

Example 4: java replaceall single character

.replaceAll("(?<!\\S)[^ ](?!\\S)", " ").trim()

Tags:

Java Example