ที่นี่เราจะมาดูวิธีการแยกจำนวนเต็มทั้งหมดออกจากสตริงใน C++ เราสามารถใส่สตริงที่มีตัวเลขและไม่มีตัวเลขได้ เราจะดึงค่าตัวเลขทั้งหมดออกมา
เพื่อแก้ปัญหานี้ เราจะใช้คลาส stringstream ใน C++ เราจะตัดสตริงทีละคำแล้วลองแปลงเป็นข้อมูลประเภทจำนวนเต็ม หากแปลงเสร็จแล้ว จะเป็นจำนวนเต็มและพิมพ์ค่า
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