Different Ways to Remove all the Digits from String in Java
Last Updated :
03 Oct, 2022
Given alphanumeric string str, the task is to write a Java program to remove all the digit from this string and prints the modified string.
Examples:
Input: str = “GeeksForGeeks123”
Output: GeeksForGeeks
Explanation: The given string contains digits 1, 2, and 3. We remove all the digit and prints the modified string.
Input: str = “12Java”
Output: Java
Explanation: The given string contains digits 1 and 2. We remove all the digit and prints the modified string.
Method 1: Using String.toCharArray() method
- Get the String to remove all the digit.
- Convert the given string into a character array.
- Initialize an empty string that stores the result.
- Traverse the character array from start to end.
- Check if the specified character is not digit then add this character into the result variable.
- Now, print the result.
Below is the implementation of the above approach:
Java
class GFG {
public static String removeAllDigit(String str)
{
char [] charArray = str.toCharArray();
String result = "" ;
for ( int i = 0 ; i < charArray.length; i++) {
if (!Character.isDigit(charArray[i])) {
result = result + charArray[i];
}
}
return result;
}
public static void main(String args[])
{
String str = "GeeksForGeeks123" ;
System.out.println(removeAllDigit(str));
}
}
|
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Method 2: Using String.charAt() method
- Get the String to remove all the digit.
- Initialize an empty string that stores the result.
- Traverse the String from start to end.
- Check if the specified character is not digit then add this character into the result variable.
- Now, print the result.
Below is the implementation of the above approach:
Java
class GFG {
public static String removeAllDigit(String str)
{
String result = "" ;
for ( int i = 0 ; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
result = result + str.charAt(i);
}
}
return result;
}
public static void main(String args[])
{
String str = "GeeksForGeeks123" ;
System.out.println(removeAllDigit(str));
}
}
|
- Time Complexity: O(N)
- Auxiliary Space: O(N)
Method 3: Using String.replaceAll() method
The idea is to use String.replaceAll() method that replaces all the sequence of characters that matches the given Regular Expression with the given replacement string.
Below is the implementation of the above approach:
Java
class GFG {
public static String removeAllDigit(String str)
{
return str.replaceAll( "\\d" , "" );
}
public static void main(String args[])
{
String str = "GeeksForGeeks123" ;
System.out.println(removeAllDigit(str));
}
}
|
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...