Given a string s consisting of lowercase letters, uppercase letters, digits, and special characters, extract all the integers present in the string and return them in the order they appear.
If no integers are present in the string, return an empty array.
Example:
Input: s = "1: Geeks for geeks, 2: geeksfor geeks, 3: forGeeksgeeks 56"
Output: [1, 2, 3, 56]
Explanation: 1, 2, 3, 56 are the integers present in s.Input: s = "geeksforgeeks"
Output: []
Explanation: No integers present in the string.
Table of Content
Using String Traversal – O(n) Time and O(n) Space
The idea is to traverse the string character by character and collect consecutive digit characters to form integers. A temporary string is used to store digits while traversing. Whenever a non-digit character is encountered, the collected number is stored in the answer vector and the temporary string is cleared. After the traversal ends, any remaining number is also added to the result.
- Traverse all characters of the string
- If the current character is a digit, append it to the temporary string
- If the temporary string is not empty, store it in the answer vector
- After traversal, store any remaining number
- Return the vector containing all extracted integers
#include<bits/stdc++.h>
using namespace std;
// Function to extract integers from
// the string str
vector<string> extractInt(string &str)
{
int n=str.size();
// This variable will store each founded
// integer temporarily
string tillNow="";
// vector to store answer
vector<string> ans;
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 store tillNow in vector
// and empty it
else{
if(tillNow.size()>0){
ans.push_back(tillNow);
tillNow="";
}
}
}
// if tillNow isn't empty then store tillNow
// in vector
if(tillNow.size()>0){
ans.push_back(tillNow);
}
return ans;
}
// Driver Code
int main()
{
string str="Hey everyone, "
"I have 500 rupees and"
" I would spend a 100";
vector<string> ans=extractInt(str);
for(string x:ans){
cout<<x<<" ";
}
return 0;
}
import java.util.*;
class GFG{
// Function to extract integers from
// the string str
public static ArrayList<String> extractInt(String str){
int n=str.length();
// This variable will store each founded
// integer temporarily
String tillNow="";
// vector to store answer
ArrayList<String> ans=new ArrayList<>();
for(int i=0;i<n;i++){
// If current character is an integer
if(str.charAt(i)-'0'>=0 &&
str.charAt(i)-'0'<=9){
tillNow+=str.charAt(i);
}
// Otherwise check if tillNow is empty
else{
if(tillNow.length()>0){
ans.add(tillNow);
tillNow="";
}
}
}
// if tillNow isn't empty then store it
if(tillNow.length()>0){
ans.add(tillNow);
}
return ans;
}
public static void main(String[] args){
String str="Hey everyone, "
+"I have 500 rupees and"
+" I would spend a 100";
ArrayList<String> ans=extractInt(str);
for(String x:ans){
System.out.print(x+" ");
}
}
}
# Function to extract integers from
# the string str
def extractInt(str):
n=len(str)
# This variable will store each founded
# integer temporarily
tillNow=""
# list to store answer
ans=[]
for i in range(n):
# If current character is an integer
if ord(str[i])-ord('0')>=0 and \
ord(str[i])-ord('0')<=9:
tillNow+=str[i]
# Otherwise check if tillNow is empty
else:
if len(tillNow)>0:
ans.append(tillNow)
tillNow=""
# if tillNow isn't empty then store it
if len(tillNow)>0:
ans.append(tillNow)
return ans
str="Hey everyone, " \
"I have 500 rupees and" \
" I would spend a 100"
ans=extractInt(str)
for x in ans:
print(x,end=" ")
using System;
using System.Collections.Generic;
class GFG{
// Function to extract integers from
// the string str
public static List<string> extractInt(string str){
int n=str.Length;
// This variable will store each founded
// integer temporarily
string tillNow="";
// list to store answer
List<string> ans=new List<string>();
for(int i=0;i<n;i++){
// If current character is an integer
if(str[i]-'0'>=0 &&
str[i]-'0'<=9){
tillNow+=str[i];
}
// Otherwise check if tillNow is empty
else{
if(tillNow.Length>0){
ans.Add(tillNow);
tillNow="";
}
}
}
// if tillNow isn't empty then store it
if(tillNow.Length>0){
ans.Add(tillNow);
}
return ans;
}
public static void Main(){
string str="Hey everyone, "
+"I have 500 rupees and"
+" I would spend a 100";
List<string> ans=extractInt(str);
foreach(string x in ans){
Console.Write(x+" ");
}
}
}
// Function to extract integers from
// the string str
function extractInt(str){
let n=str.length;
// This variable will store each founded
// integer temporarily
let tillNow="";
// array to store answer
let ans=[];
for(let i=0;i<n;i++){
// If current character is an integer
if(str[i]-'0'>=0 &&
str[i]-'0'<=9){
tillNow+=str[i];
}
// Otherwise check if tillNow is empty
else{
if(tillNow.length>0){
ans.push(tillNow);
tillNow="";
}
}
}
// if tillNow isn't empty then store it
if(tillNow.length>0){
ans.push(tillNow);
}
return ans;
}
let str="Hey everyone, "
+"I have 500 rupees and"
+" I would spend a 100";
let ans=extractInt(str);
for(let x of ans){
process.stdout.write(x+" ");
}
Output
500 100
[Regex Approach] Using Regular Expressions – O(n) Time and O(n) Space
The idea is to use regular expressions to directly find all continuous sequences of digits present in the string. The regex pattern
\\d+matches one or more consecutive digit characters.
- Create a regex pattern:
\\d+→ matches continuous digits - Use
regex_search()to find integers in the string - Store every matched number in the result vector
- Continue searching in the remaining suffix of the string
- Return all extracted integers
#include<bits/stdc++.h>
using namespace std;
// Function to extract integers from the string str using regex
vector<string> extractInt(string &str)
{
vector<string> ans;
// Regex pattern to find one or more digits
regex pattern("\\d+");
// Iterator to find matches
smatch matches;
string temp = str;
// Search for pattern in the string
while(regex_search(temp, matches, pattern)) {
// Add the found integer to result
ans.push_back(matches[0]);
// Continue searching in remaining string
temp = matches.suffix();
}
return ans;
}
// Driver Code
int main()
{
string str = "Hey everyone, I have 500 rupees and I would spend a 100";
vector<string> ans = extractInt(str);
for(string x : ans) {
cout << x << " ";
}
return 0;
}
// Java program to extract integers from string without regex
import java.util.*;
class GfG {
// Function to extract integers from the string
static List<String> extractInt(String str) {
List<String> ans = new ArrayList<>();
String num = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// If current character is a digit
if (ch >= '0' && ch <= '9') {
num = num + ch;
} else {
// If we have a number in buffer, add it to result
if (num.length() > 0) {
ans.add(num);
num = "";
}
}
}
// Check if there's a number at the end of string
if (num.length() > 0) {
ans.add(num);
}
return ans;
}
// Driver Code
public static void main(String[] args) {
String str = "Hey everyone, I have 500 rupees and I would spend a 100";
List<String> ans = extractInt(str);
for (String x : ans) {
System.out.print(x + " ");
}
}
}
# Python program to extract integers from string using regex
import re
# Function to extract integers from the string using regex
def extractInt(s):
# Regex pattern to find one or more digits
pattern = r"\d+"
# Find all matches in the string
ans = re.findall(pattern, s)
return ans
# Driver Code
if __name__ == "__main__":
s = "Hey everyone, I have 500 rupees and I would spend a 100"
ans = extractInt(s)
for x in ans:
print(x, end=" ")
// C# program to extract integers from string using regex
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class GfG {
// Function to extract integers from the string using regex
static List<string> extractInt(string str) {
List<string> ans = new List<string>();
// Regex pattern to find one or more digits
Regex pattern = new Regex(@"\d+");
// Find all matches in the string
MatchCollection matches = pattern.Matches(str);
// Add each match to result
foreach (Match match in matches) {
ans.Add(match.Value);
}
return ans;
}
// Driver Code
static void Main(string[] args) {
string str = "Hey everyone, I have 500 rupees and I would spend a 100";
List<string> ans = extractInt(str);
foreach (string x in ans) {
Console.Write(x + " ");
}
}
}
// JavaScript program to extract integers from string using regex
// Function to extract integers from the string using regex
function extractInt(str) {
// Regex pattern to find one or more digits (global flag for all matches)
const pattern = /\d+/g;
// Find all matches in the string
const ans = str.match(pattern) || [];
return ans;
}
// Driver Code
const str = "Hey everyone, I have 500 rupees and I would spend a 100";
const ans = extractInt(str);
console.log(ans.join(" "));
Output
500 100