Extract all integers from the given string in Java
Given a string str consisting of digits, alphabets and special characters. The task is to extract all the integers from the given string.
Input: str = “geeksforgeeks A-118, Sector-136, Uttar Pradesh-201305”
Output: 118 136 201305
Input: str = ” 1abc35de 99fgh, dd11″
Output: 1 35 99 11
- 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:
1122 4 543
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.