Extract all integers from a given String
Given a string str, extract all integers words from it.
Example:
Input: str = “1Hello2 &* how are y5ou”
Output: 1 2 5Input: str = “Hey everyone, I have 500 rupees and I would spend a 100”
Output: 500 100
Approach: To solve this problem follow the below steps:
- Create a string tillNow, which will store all founded integers till now. Initialise it with an empty string.
- Now start traversing string str, and in each iteration:
- If a character is a number, add it to the string tillNow.
- Otherwise, check if the string tillNow is empty or not. If it isn’t empty, then convert it to an integer and empty it after printing it.
- Now, after the loop ends, check again that if the string tillNow is empty or not. If it isn’t then, convert it to integer and print it.
Below is the implementation of the above approach
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Function to extract integers from// the string strvoid extractIntegers(string str){ int n = str.size(); // This variable will store each founded // integer temporarily string tillNow = ""; for (int i = 0; i < n; i++) { // If current character is an integer, then // add it to string tillNow if (str[i] - '0' >= 0 and str[i] - '0' <= 9) { tillNow += str[i]; } // Otherwise, check if tillNow is empty or not // If it isn't then convert tillNow to integer // and empty it after printing else { if (tillNow.size() > 0) { cout << stoi(tillNow) << ' '; tillNow = ""; } } } // if tillNow isn't empty then convert tillNow // to integer and print it if (tillNow.size() > 0) { cout << stoi(tillNow) << ' '; }}// Driver Codeint main(){ string str = "Hey everyone, " "I have 500 rupees and" " I would spend a 100"; extractIntegers(str);} |
Java
// Java program for the above approachclass GFG{// Function to extract integers from// the String strstatic void extractIntegers(char []str){ int n = str.length; // This variable will store each founded // integer temporarily String tillNow = ""; for (int i = 0; i < n; i++) { // If current character is an integer, then // add it to String tillNow if (str[i] - '0' >= 0 && str[i] - '0' <= 9) { tillNow += str[i]; } // Otherwise, check if tillNow is empty or not // If it isn't then convert tillNow to integer // and empty it after printing else { if (tillNow.length() > 0) { System.out.print(Integer.parseInt(tillNow) +" "); tillNow = ""; } } } // if tillNow isn't empty then convert tillNow // to integer and print it if (tillNow.length() > 0) { System.out.print(Integer.parseInt(tillNow) +" "); }}// Driver Codepublic static void main(String[] args){ String str = "Hey everyone, " +"I have 500 rupees and" +" I would spend a 100"; extractIntegers(str.toCharArray());}}// This code is contributed by 29AjayKumar |
Python3
# Python3 program for the above approach# Function to extract integers from# the string strdef extractIntegers(string) : n = len(string); # This variable will store each founded # integer temporarily tillNow = ""; for i in range(n) : # If current character is an integer, then # add it to string tillNow if (ord(string[i]) - ord('0') >= 0 and ord(string[i]) - ord('0') <= 9) : tillNow += string[i]; # Otherwise, check if tillNow is empty or not # If it isn't then convert tillNow to integer # and empty it after printing else : if (len(tillNow) > 0) : print(int(tillNow),end = ' '); tillNow = ""; # if tillNow isn't empty then convert tillNow # to integer and print it if (len(tillNow) > 0) : print(int(tillNow),end = ' ');# Driver Codeif __name__ == "__main__" : string = "Hey everyone, I have 500 rupees and I would spend a 100"; extractIntegers(string); # This code is contributed by AnkThon |
C#
// C# program for the above approachusing System;class GFG{ // Function to extract integers from // the String str static void extractIntegers(char[] str) { int n = str.Length; // This variable will store each founded // integer temporarily String tillNow = ""; for (int i = 0; i < n; i++) { // If current character is an integer, then // add it to String tillNow if (str[i] - '0' >= 0 && str[i] - '0' <= 9) { tillNow += str[i]; } // Otherwise, check if tillNow is empty or not // If it isn't then convert tillNow to integer // and empty it after printing else { if (tillNow.Length > 0) { Console.Write(int.Parse(tillNow) + " "); tillNow = ""; } } } // if tillNow isn't empty then convert tillNow // to integer and print it if (tillNow.Length > 0) { Console.Write(int.Parse(tillNow) + " "); } } // Driver Code public static void Main(String[] args) { String str = "Hey everyone, " + "I have 500 rupees and" + " I would spend a 100"; extractIntegers(str.ToCharArray()); }}// This code is contributed by Saurabh Jaiswal |
Javascript
<script>// Javascript program for the above approach// Function to extract integers from// the string strfunction extractIntegers(str) { let n = str.length; // This variable will store each founded // integer temporarily let tillNow = ""; for (let i = 0; i < n; i++) { // If current character is an integer, then // add it to string tillNow if (str[i].charCodeAt(0) - '0'.charCodeAt(0) >= 0 && str[i].charCodeAt(0) - '0'.charCodeAt(0) <= 9) { tillNow += str[i]; } // Otherwise, check if tillNow is empty or not // If it isn't then convert tillNow to integer // and empty it after printing else { if (tillNow.length > 0) { document.write(tillNow + ' '); tillNow = ""; } } } // if tillNow isn't empty then convert tillNow // to integer and print it if (tillNow.length > 0) { document.write(tillNow + ' '); }}// Driver Codelet str = "Hey everyone, I have 500 rupees and I would spend a 100";extractIntegers(str);// This code is contributed by gfgking.</script> |
Output
500 100
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach 2: Using Regex
Java
/*package whatever //do not write package name here */import java.util.*;class GFG { static void extractIntegers(String sentence) { // Split string using regex so only the string will // be available that only made up of digits Regex // Explaination -> // [^...]+ matches the all character except present // in square bracket with as many as possible // characters {4} -> To match the string whose // length is four String splittedWords[] = sentence.split( "[^0-9]+"); // Can also split with "[a-zA-Z()._ // -]+{4}" // Print the Extracted Integers for (String i : splittedWords) System.out.print(i + " "); } public static void main(String[] args) { String sentence1 = "Hey everyone I have 500 rupees and I would spend a 100"; extractIntegers(sentence1); }} |
Output
500 100



Please Login to comment...