Extract all integers from a given String

27 Dec, 2021
Given a string str, extract all integers words from it.
Example:
Input: str = “1Hello2   &* how  are y5ou”Output: 1 2 5
Input: 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.
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.
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.
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++
Java
Python3
C#
Javascript
// 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 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 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# 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
<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>
500 100 
Time Complexity: O(N)Auxiliary Space: O(N)
rakeshsahni
gfgking
ankthon
29AjayKumar
_saurabh_jaiswal
arorakashish0911
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Python Exception Handling
Python Try Except
Ternary Operator in Python
Write a program to reverse an array or string
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4
KMP Algorithm for Pattern Searching