C++ 使用 stringstream與getline()分割字符串

stringstream

頭文件 #include
stringstream 可以使string與各種內置類型數據之間的轉換,本文不做講解
本文主要利用其流的特性;
基本語法

//輸入
stringstream ss1;
ss1<< "qwe";

//輸出
string str;
stringstream ss2("qwe");
ss2 >>str ;

getline()

頭文件:
getline()的原型是istream& getline ( istream &is , string &str , char delim );
其中 istream &is 表示一個輸入流,
例如,可使用cin;
string str ; getline(cin ,str)
也可以使用 stringstream
stringstream ss("test#") ; getline(ss,str)
char delim表示遇到這個字符停止讀入,通常系統默認該字符爲’\n’,也可以自定義字符

字符串分割

當我們直接利用getline(),自定義字符,從cin流中分割字符,例如
輸入 “one#two”

string str;		
ss << str2;
while (getline(cin, str, '#'))
	cout << str<< endl;
system("pause");
return 0;

輸出結果爲
one
後面的 two並沒有輸出
此時如果我們是用stringstream 流
例如

int main()
{
	string str;	
	string str_cin("one#two#three");
	stringstream ss;
	ss << str_cin;
	while (getline(ss, str, '#'))
		cout << str<< endl;
	system("pause");
	return 0;
}

得到的結果爲

one
two
three

因此,如果我們想得到類似於split 函數的效果
可以使用 stringstream 與getline 結合的方法

c++ 實現 split

vector<string> split(string str, char del) {
	stringstream ss(str);
	string temp;
	vector<string> ret;
	while (getline(ss, temp, del)) {
		ret.push_back(temp);
	}
	return ret;
}
int main()
{
	string str_cin("one#two#three");
	vector<string> res= split(str_cin, '#');
	for (auto c : res)
		cout << c << endl;
	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章