Wednesday 18 May 2022

How to remove special characters from a string?

In this post, I am going to explain how to remove special characters from a string.

 

Approach 1: Using Character.isAlphabetic or Character.isDigit method.

 

Example

StringBuilder builder = new StringBuilder();
		
for(char ch : str.toCharArray()) {
	if(Character.isAlphabetic(ch) || Character.isDigit(ch)) {
		builder.append(ch);
	}
}

 

Find the below working application.

 


ReplaceSpecialCharsDemo1.java

package com.sample.app;

public class ReplaceSpecialCharsDemo1 {
	
	public static void main(String[] args) {
		String str = "Hello@@#123$%%There";
			
		StringBuilder builder = new StringBuilder();
		
		for(char ch : str.toCharArray()) {
			if(Character.isAlphabetic(ch) || Character.isDigit(ch)) {
				builder.append(ch);
			}
		}
		
		System.out.println(builder.toString());
	}

}

 

Approach 2: Using regular expressions.

String result = str.replaceAll("[^\\w\\s]", "");

 

Above snippet replace all the non-alpha numeric characters with a space.

 

Find the below working application.

 

ReplaceSpecialCharsDemo2.java

package com.sample.app;

public class ReplaceSpecialCharsDemo2 {

	public static void main(String[] args) {
		String str = "Hello@@#123$%%There";
		String result = str.replaceAll("[^\\w\\s]", "");

		System.out.println("result : " + result);
	}

}

 

Output

result : Hello123There

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment