从 C++ 字符串中提取所有整数
在此我们将了解如何在 C++ 中从字符串中提取所有整数。字符串中存在数字和非数字,我们将从字符串中提取所有数值。
为了解决此问题,我们将使用 C++ 中的 stringstream 类。我们将逐词切割字符串,然后尝试将字符串转换为整数类型数据。如果转换完成,则为整数并打印值。
Input: A string with some numbers “Hello 112 World 35 75” Output: 112 35 75
算法
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
示例代码
#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);
}输出
112 35 75
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP