Home Tutorial Java Core Java String : Replace All

 
 

Java String : Replace All
Posted on: November 23, 2012 at 12:00 AM
Advertisement
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.
Advertisement

Related Tags for Java String : Replace All:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 23, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com