【千律】C++基础:根据指定字符“#”对字符串进行分割,将分割后的字符串存储在vector动态数组中

【千律】C++基础:根据指定字符“#”对字符串进行分割,将分割后的字符串存储在vector动态数组中,第1张

#include 
#include 
#include 
using namespace std;

int main()
{
	// 初始化变量
	string str_cctry = "#123#abc#cctry.com#";
	vector vec_cctry;

	// 判断字符串中是否存在“#”字符
	while (str_cctry.find("#") != -1)
	{
		// 获取“#”字符存在的位置
		int object_num = str_cctry.find("#");

		// 根据获取的位置,对字符串进行截取
		string sub_cctry = str_cctry.substr(0, object_num);

		// 若字符串非空,将截取字符串存储在动态数组中
		if (!sub_cctry.empty())
		{
			vec_cctry.push_back(sub_cctry);
		}

		// 更新字符串
		str_cctry.erase(0, sub_cctry.length() + 1);
	} 

	// 若存在剩余字符串将剩余字符串存储在动态数组中
	if (!str_cctry.empty())
	{
		vec_cctry.push_back(str_cctry);
	}
	
	// 循环输出动态数组中存储变量
	for (int i = 0; i < int(vec_cctry.size()); i++)
	{
		cout << vec_cctry[i] << endl;
	}

	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/584996.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-12
下一篇2022-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存