Extract all integers from a given String
Last Updated :
19 Apr, 2023
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.
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>
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__
Similar Reads
Extract all integers from string in C++ Given a string, extract all integers words from it. Examples : Input : str = "geeksforgeeks 12 13 practice" Output : 12 13 Input : str = "1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta" Output : 1 2 3 Input : str = "Ankit sleeps at 4 am." Output : 4 The idea is to use stringstream:, objec
2 min read
Extract 'k' bits from a given position in a number. How to extract 'k' bits from a given position 'p' in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is repr
4 min read
Python Slicing | Extract âkâ bits from a given position How to extract âkâ bits from a given position âpâ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is repr
4 min read
Extract maximum numeric value from a given string | Set 2 (Regex approach) Given an alphanumeric string, extract maximum numeric value from that string. Examples: Input : 100klh564abc365bg Output : 564 Maximum numeric value among 100, 564 and 365 is 564. Input : abchsd0365sdhs Output : 365Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. I
7 min read
Find the valid integer from given String Given a string str of size N, containing ' ', '.', '-', '+', and ['0'-'9'], the task is to find the valid integer from this string.An integer is known as valid if follows the following rules: If str has leading whitespaces, ignore them.The first valid character should be '-', '+', or ['0'-'9']If no
8 min read
Extract maximum numeric value from a given string | Set 1 (General approach) Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. One approach to solving the problem is discussed here, other using Regular expressions is given in Set 2 Examples: Input : 100klh564abc365bg Output : 564 Maximum numeric value among 10
12 min read