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 str void 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 Code int main() { string str = "Hey everyone, " "I have 500 rupees and" " I would spend a 100" ; extractIntegers(str); } |
Java
// Java program for the above approach 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 ) { 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 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 29AjayKumar |
Python3
# Python3 program for the above approach # Function to extract integers from # the string str def 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 Code if __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 approach using 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 str function 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 Code let 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
C++
#include <bits/stdc++.h> using namespace std; void extractIntegers(string sentence) { // Split string using regex so only the string will // be available that only made up of digits Regex // Explanation -> // [^...]+ matches the all character except present // in square bracket with as many as possible // characters {4} -> To match the string whose // length is four stringstream ss(sentence); string temp; vector< int > integers; while (ss >> temp) { if (temp[0] >= '0' && temp[0] <= '9' ) { integers.push_back(stoi(temp)); } } // Print the Extracted Integers for ( int i : integers) cout << i << " " ; } int main() { string sentence1 = "Hey everyone I have 500 rupees and " "I would spend a 100" ; extractIntegers(sentence1); return 0; } // This code is contributed by akashish__ |
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 // Explanation -> // [^...]+ 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); } } |
Python3
import re def extract_integers(sentence): # Split string using regex so only the string will # be available that only made up of digits Regex # Explanation -> # [^...]+ matches the all character except present # in square bracket with as many as possible # characters {4} -> To match the string whose # length is four splitted_words = re.findall(r '\b\d+\b' , sentence) # Print the Extracted Integers for i in splitted_words: print (i, end = " " ) sentence1 = "Hey everyone I have 500 rupees and I would spend a 100" extract_integers(sentence1) # This code is contributed by akashish__ |
C#
using System; using System.Linq; using System.Text.RegularExpressions; public 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 // Explanation -> // [^...]+ 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 = Regex.Split(sentence, "[^0-9]+" ); // Print the Extracted Integers foreach ( string i in splittedWords) { if (! string .IsNullOrEmpty(i)) { Console.Write(i + " " ); } } } static public void Main() { string sentence1 = "Hey everyone I have 500 rupees and I would spend a 100" ; extractIntegers(sentence1); } } // this code is contributed by akashish__ |
Javascript
function extractIntegers(sentence) { // Split string using regex so only the string will // be available that only made up of digits Regex // Explanation -> // [^...]+ matches the all character except present // in square bracket with as many as possible // characters {4} -> To match the string whose // length is four let splittedWords = sentence.match(/\b\d+\b/g); // Can also split with "[a-zA-Z()._ // -]+{4}" // Print the Extracted Integers for (let i = 0; i < splittedWords.length; i++) { console.log(splittedWords[i], " " ); } } let sentence1 = "Hey everyone I have 500 rupees and I would spend a 100" ; extractIntegers(sentence1); // This code is contributed by akashish__ |
Output
500 100
Contact Us