從 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

更新日期: 2019-07-30

6K+ 瀏覽量

開啟你的 職業 生涯

完成課程並獲得認證

開始
廣告