Extract all integers from string in C++

Given a string, extract all integers words from it. Examples :
Input : str = "zambiatek 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:, objects of this class use a string buffer that contains a sequence of characters.
Algorithm:
- Enter the whole string into stringstream.
- Extract the all words from string using loop.
- Check whether a word is integer or not.
Implementation:
CPP
/* Extract all integers from string */#include <iostream>#include <sstream>using namespace std;void extractIntegerWords(string str){ stringstream ss; /* Storing the whole string into string stream */ ss << str; /* Running loop till the end of the stream */ string temp; int found; while (!ss.eof()) { /* extracting word by word from stream */ ss >> temp; /* Checking the given word is integer or not */ if (stringstream(temp) >> found) cout << found << " "; /* To save from space at the end of string */ temp = ""; }}// Driver codeint main(){ string str = "1: 2 3 4 prakhar"; extractIntegerWords(str); return 0;} |
Output
1 2 3 4
Time Complexity: O(N), where, N is the length of the string.
Auxiliary Space: O(1), We are not using any extra space.
Related Articles :
- Converting string to number and vice-versa in C++
- Program to extract words from a given String
- Removing spaces from a string using Stringstream
This article is contributed by Prakhar Agrawal. If you like zambiatek and would like to contribute, you can also write an article using contribute.zambiatek.com or mail your article to contribute@zambiatek.com. See your article appearing on the zambiatek main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



