C++ string 截取字符串,字符串分割

本文介绍了一种字符串分割的方法,并提供了一个具体的C++实现示例。通过使用自定义的字符串分割函数StrSplit,可以将输入的字符串根据指定的分隔符进行拆分,并返回一个包含所有子字符串的vector容器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串分割实现示例:

#include <string>
#include <vector>
#include <iostream>
using namespace std;

//字符串分割函数
vector<string> StrSplit(string strUserInfo, string strSplitPoint)
{
	string::size_type strPos;
	vector<string> vResult;
	int nSize = strUserInfo.size();
	for (int i = 0; i < nSize; i++)
	{
		strPos = strUserInfo.find(strSplitPoint, i);
		if (strPos < nSize)
		{
			std::string s = strUserInfo.substr(i, strPos - i);
			vResult.push_back(s);
			i = strPos + strSplitPoint.size() - 1;
		}
	}
	return vResult;
}

int main() {

	string strUserInfo = "H e l l o W o r d !";
	vector<string> vResult = StrSplit(strUserInfo, " ");
	for (int i = 0; i < vResult.size(); i++)
	{
		cout << "[" << vResult[i] << "]" << endl;
	}

	return 0;
}

输出显示:

结果显示

substr()函数:按照条件截取字符串

原型:string substr (size_t pos = 0, size_t len = npos) const;
参数说明:pos=截取起始位 ,len=截取长度。
返回值:子字符串

鼠标单击链接跳转到对应网址: substr释义.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值