C++分割帶逗號的字串
阿新 • • 發佈:2018-12-11
我們知道,C++預設通過空格(或回車)來分割字串輸入,即區分不同的字串輸入。但是有時候,我們得到的字串是用逗號來分割的,給我們使用者帶來極大的不便。
那麼,有什麼辦法能更加方便的使用這些字串呢?其實,C++提供了一種方法(我目前所知道的)來解決這個問題。
1. 解決方法
C++提供了一個類 istringstream ,其建構函式原形如下:
istringstream::istringstream(string str);
它的作用是從 string 物件 str 中讀取字元。
那麼我們可以利用這個類來解決問題,方法如下:
第一步:接收字串 s ;
第二步:遍歷字串 s ,把 s 中的逗號換成空格;
第三步:通過 istringstream
注意, istringstream 這個類包含在庫 < sstream > 中,所以標頭檔案必須包含這個庫。
2. 程式碼實現
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
string s = "ab,cd,e,fg,h";
int n = s.size();
for (int i = 0; i < n; ++i){
if (s[i] == ','){
s[i] = ' ';
}
}
istringstream out(s);
string str;
while (out >> str){
cout << str <<' ';
}
cout << endl;
}
輸出結果如下: