我們知道,C++默認通過空格(或回車)來分割字符串輸入,即區分不同的字符串輸入。但是有時候,我們得到的字符串是用逗號來分割的,給我們使用者帶來極大的不便。
那么,有什么辦法能更加方便的使用這些字符串呢?其實,C++提供了一種方法(我目前所知道的)來解決這個問題。
1. 解決方法
C++提供了一個類 istringstream ,其構造函數原形如下:
istringstream::istringstream(string str);
- 1
它的作用是從 string 對象 str 中讀取字符。
那么我們可以利用這個類來解決問題,方法如下:
第一步:接收字符串 s ;
第二步:遍歷字符串 s ,把 s 中的逗號換成空格;
第三步:通過 istringstream 類重新讀取字符串 s ;
注意, 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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
輸出結果如下:
</div>