Java String Program · S10
Remove Special Characters From a String in Java
Strip everything except letters and digits from a string, for example to build a username or a search key. Compare a hand-written loop with a one-line regex.
Problem Statement
Write a method that removes every character that is not an English letter (A to Z, a to z) or a digit (0 to 9).
Spaces and underscores are removed too, and the remaining characters keep their order. If nothing is left, return an empty string.
Input/Output Examples
"Hi! 17"Output"Hi17"Explanation: the ! and the space are removed."@user_name#1"Output"username1"Explanation: @, _ and # are not letters or digits."#$%"Output""Explanation: every character is removed.Visual Explanation
"Hi! 17": letters and digits are kept (purple) and appended to the result; the ! and the space are dropped.Each character is tested once against three ranges: lowercase letters, uppercase letters and digits. Kept characters are appended to a StringBuilder, so their original order is preserved.
Approaches
The loop shows every rule explicitly. The regex expresses the same rule as a pattern.
Approach 1: StringBuilder Loop (Recommended)
Idea: append only the characters that fall in a-z, A-Z or 0-9.
- Create a
StringBuilderwith the input length as its capacity. - For each character, check the three ranges.
- Append the character if it matches, then return
toString().
Time: O(n) · Space: O(n). The result can be as long as the input.
Approach 2: replaceAll() With a Regex
Idea: replace every character that matches [^A-Za-z0-9], meaning "not a letter or digit", with an empty string.
- Inside square brackets,
^negates the character class. A-Za-z0-9lists the characters to keep.replaceAll()removes every match in one call.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: StringBuilder Loop (Recommended)
Setting the initial capacity avoids resizing the builder. This version needs no regex knowledge and is easy to adapt, for example to keep spaces.
public class RemoveSpecialLoop {
// Keeps only A-Z, a-z and 0-9; everything else, including spaces, is dropped
static String removeSpecial(String text) {
StringBuilder result = new StringBuilder(text.length());
for (char c : text.toCharArray()) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String[] inputs = {"Hi! 17", "@user_name#1", "#$%"};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + removeSpecial(text) + "\"");
}
}
}
"Hi! 17" -> "Hi17" "@user_name#1" -> "username1" "#$%" -> ""
Time complexity: O(n) · Space complexity: O(n).
Approach 2: replaceAll() With a Regex
The most concise solution. String.replaceAll() compiles the pattern on every call, so code that cleans many strings should compile it once with Pattern.compile().
public class RemoveSpecialRegex {
// [^A-Za-z0-9] matches any character that is NOT a letter or digit
static String removeSpecial(String text) {
return text.replaceAll("[^A-Za-z0-9]", "");
}
public static void main(String[] args) {
String[] inputs = {"Hi! 17", "@user_name#1", "#$%"};
for (String text : inputs) {
System.out.println("\"" + text + "\" -> \"" + removeSpecial(text) + "\"");
}
}
}
"Hi! 17" -> "Hi17" "@user_name#1" -> "username1" "#$%" -> ""
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| StringBuilder Loop | O(n) | O(n) |
| replaceAll() With a Regex | O(n) | O(n) |
Here n is the length of the string. Both approaches scan the input once and build a new string of up to n characters.
Interview Tips and Recommended Approach
- Ask what "special" means. Should spaces stay? Should accented letters such as
éstay? The answer changes the character ranges or the regex. - Know the regex variants.
[^A-Za-z0-9 ]keeps spaces, and[^\\p{L}\\p{Nd}]keeps letters and digits from every language. - Avoid string concatenation in a loop.
result += ccreates a new string each time; use aStringBuilder. - Remember that the original string does not change.
replaceAll()returns a new string, so you must use its return value.
Recommended Approach: StringBuilder Loop
Why: it is fast, needs no regex engine and makes the kept characters explicit, which matters when an interviewer asks for a solution without regular expressions. In everyday code, the one-line replaceAll() is a fine alternative.