Extract all integers from the given string in Java
Last Updated :
28 Mar, 2023
Given a string str consisting of digits, alphabets, and special characters. The task is to extract all the integers from the given string.
Examples:
Input: str = "geeksforgeeks A-118, Sector-136, Uttar Pradesh-201305"
Output: 118 136 201305
Input: str = " 1abc35de 99fgh, dd11"
Output: 1 35 99 11
Approach 1:
- Replace all the non-digit characters with spaces (” “).
- Now replace every consecutive group of spaces with a single space.
- Eliminate the leading and the trailing spaces (if any) and the final string will only contain the required integers.
Below is the implementation of the above approach:
Java
public class GFG {
static String extractInt(String str)
{
str = str.replaceAll("[^\\d] & quot;, "
");
str = str.trim();
str = str.replaceAll(" + ", "
");
if (str.equals(" "))
return "
- 1 & quot;
;
return str;
}
public static void main(String[] args)
{
String str = "
avbkjd1122klj4 543 af& quot;
;
System.out.print(extractInt(str));
}
}
|
Time Complexity: O(n), Here n is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.
Approach 2:
Java
public class GFG {
static String extractInt(String str)
{
str = str.replaceAll( "[^0-9]" , " " );
str = str.replaceAll( " +" , " " );
if (str.equals( "" ))
return "-1" ;
return str;
}
public static void main(String[] args)
{
String str = "avbkjd1122klj4 543 af" ;
System.out.print(extractInt(str));
}
}
|
Time Complexity: O(n), Here n is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.
Share your thoughts in the comments
Please Login to comment...