Share on Google+Share on Google+

Java String : Replace All

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.

Advertisements

Posted on: November 23, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.