c++分割字符串方法(char*、string)

char*类型

使用c库函数strtok

函数原型: char *strtok(char *str, const char *delim);
分割字符串返回一串字符;
strtok会将分类字符‘,’改为‘\0’,strtok之间会有缓存(使用NULL,继续分割)

#include<iostream>
using namespace std;
int main() {
	char str[] = "1,2,3,4,5,6";
	char split = ',';
	char* ans;
	ans = strtok(str, &split);
	//返回(char*)的1
	while (ans != nullptr) {
		cout << *ans << " ";
		ans = strtok(NULL, &split);
		//继续分割,返回剩下字符
	}

}

string类型

使用find+substr函数

函数原型:string substr ( size_t pos = 0, size_t n = npos ) const;

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
	string str = "1,2,3,4,5,6";
	vector<string>ans;
	char split = ',';
	int str_len = str.size();
	int spos = 0;
	//开始找的位置
	int epos = 0;
	//找到的首位置
	while(epos =str.find(split, spos))
		if (epos == -1) {
		//等于-1说明没有‘,’了但还有一个6要拿出来
			string temp = str.substr(spos, str_len - spos);
			ans.push_back(temp);
			break;
		}
		else {
			string temp = str.substr(spos, epos - spos);
			//分割spos到epos的字符
			ans.push_back(temp);
			spos = epos + 1;
			//越过‘,’继续找
		}
	for (auto x : ans) {
		cout << x << " ";
	}
	
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值