C++分割带逗号的字符串

C++分割带逗号的字符串

我们知道,C++默认通过空格(或回车)来分割字符串输入,即区分不同的字符串输入。但是有时候,我们得到的字符串是用逗号来分割的,给我们使用者带来极大的不便。
那么,有什么办法能更加方便的使用这些字符串呢?其实,C++提供了一种方法(我目前所知道的)来解决这个问题。

1. 解决方法

C++提供了一个类 istringstream ,其构造函数原形如下:

istringstream::istringstream(string str);

它的作用是从 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;
}

输出结果如下:
输出结果

猜你喜欢

转载自blog.csdn.net/qq_35481167/article/details/82827527
今日推荐