将字符串分成多个字符串输出

substr函数:截取字符串中的部分字符串。

string substr(int n = 0, int m = string::npos) const; //起点为n,长度为m。

调用时,如果省略 m 或 m 超过了字符串的长度,则求出来的子串就是从下标 n 开始一直到字符串结束的部分。

下面代码功能:

输入一个字符串,当出现“,”时,形成新的短字符串。

如输入:few,tew,rwe     

则输出:

few

tew

rwe

#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int N = 10000;
int main()
{
	string a;
	getline(cin, a);
	int n = a.size();
	vector<int> b;
	string c;  //输出字符
	for (int i = 0; i <n; i++)
	{
		if (a[i] == ',')
		{
			b.push_back(i);
		}
	}
	int m = b.size();

	c = a.substr(0, b[0]);  //第一个字符串从0开始,长度为b[0];
	cout << c << endl;

	for (int i = 0; i < m; i++)
	{
		if (i == m - 1)
		{
			c = a.substr(b[m - 1] + 1);
			cout << c << endl;
		}
		else 
		{
			c = a.substr(b[i] + 1, b[i + 1] - b[i] - 1);
			cout << c<<endl;
		}
	}
}

     运行结果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章