Java String : Replace All


 

Java String : Replace All

This section defines how to replace all character with specified character without using system methods.

This section defines how to replace all character with specified character without using system methods.

Java String : Replace All

This section defines how to replace all character with specified character without using system methods.

Replace All method :

You can replace all specific character in a given string with another character by using String method replaceAll() or by writing your own logic.

Example : In this example we are replacing all blank spaces by the special character  ' * '. For that we have written simple logic. There is also direct method to replace all spaces by calling one of String method replaceAll("  ", "*" ). Here we are writing simple logic -

class ReplaceAll {
	public static void main(String[] args) {
		String str = "Hello world. Welcome to the wonderland.";
		String str1 = new String();
		char[] ch = str.toCharArray();
		int l = str.length();
		for (int i = 0; i < l; i++) {
			if (ch[i] == ' ') {
				ch[i] = '*';
			}
		}
		for (int i = 0; i < l; i++) {
			str1 = str1 + ch[i];
		}
		System.out.println("Orignal String : " + str);
		System.out.println("After replacing blank space to * our String : "
				+ str1);
	}
}

Output :

Orignal String : Hello world. Welcome to the wonderland.
After replacing blank space to * our String : Hello*world.*Welcome*to*the*wonderland.

Ads