Remove Digits from a String in Java
Problem
A digit is any of the characters 0 through 9 that can appear inside a string alongside letters and symbols.
Given a string, remove every digit it contains.
Java Program
public class RemoveDigits {
public static void main(String[] args) {
String str = "Order66Confirmed42";
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) result.append(c); // skip digits entirely
}
System.out.println(result.toString());
}
}Output
Core Logic
Keeping every character that isn't a digit, one pass through the string, filters out the digits and leaves everything else in place.
- 1A for-each loop visits each character of the string in turn.
- 2
Character.isDigit(c)checks whether the current character is one of0through9. - 3Characters that fail the check are appended to a
StringBuilder; digits are simply skipped. - 4The final
StringBuilderholds every original character except the digits.
"Order66Confirmed42", the digits 6, 6, 4, and 2 are skipped, producing "OrderConfirmed".Key Point: This mirrors the digit-counting program exactly, just appending non-digits to a result instead of incrementing a counter for digits.
Why: Each character is visited once and the result buffer grows to hold every non-digit character, which can be up to n.
Key Concepts
Approach 2: Java 8
import java.util.stream.Collectors;
public class RemoveDigitsStream {
public static void main(String[] args) {
String str = "Order66Confirmed42";
// Keeps every character that isn't a digit, then joins them back into a String
String result = str.chars()
.filter(c -> !Character.isDigit(c))
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
System.out.println(result);
}
}
Output
Core Logic
The same is-not-a-digit check can filter a stream of character codes, then join what's left back into a string.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.filter(c -> !Character.isDigit(c))keeps only the codes that are NOT a digit. - 3
.mapToObj(c -> String.valueOf((char) c))converts each surviving code back into a one-characterString. - 4
.collect(Collectors.joining())concatenates them all back into a single result string.
"Order66Confirmed42" drops every digit, and joining what's left reassembles "OrderConfirmed".Key Point: Negating Character::isDigit with ! flips the same check the loop version uses directly — streams just change how it's applied.
Why: The stream still visits every character once, and Collectors.joining() builds a result string holding every non-digit character.