- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract all integers from string in C++
Here we will see how to extract all integers from strings in C++. We can put a string where numbers and no-numbers are present. We will extract all numeric values from it.
To solve this problem, we will use the stringstream class in C++. We will cut the string word by word and then try to convert it into integer type data. if the conversion is done, then it is integer and print the value.
Input: A string with some numbers “Hello 112 World 35 75” Output: 112 35 75
Algorithm
Step 1:Take a number string Step 2: Divide it into different words Step 3: If a word can be converted into integer type data, then it is printed Step 4: End
Example Code
#include<iostream> #include<sstream> using namespace std; void getNumberFromString(string s) { stringstream str_strm; str_strm << s; //convert the string s into stringstream string temp_str; int temp_int; while(!str_strm.eof()) { str_strm >> temp_str; //take words into temp_str one by one if(stringstream(temp_str) >> temp_int) { //try to convert string to int cout << temp_int << " "; } temp_str = ""; //clear temp string } } main() { string my_str = "Hello 112 World 35 75"; getNumberFromString(my_str); }
Output
112 35 75
Advertisements