一个简单的c++小功能,将字符串按照某个字符剪切成数组

有两种返回方式,一种是注释掉的vector,另一种是指针类型,两种都可以用。不适合大神看。哈哈哈
头文件split.h

#pragma once
#include<vector>
#include<string>
#define LEN 100
using namespace std;
//vector<string> s;
//vector<string> split(const string str, const string ch) {
//	string str2 = str + ch;
//	while (str2.find(ch) <= str.size()) {
//		s.push_back(str2.substr(0, str2.find(ch)));
//		str2 = str2.substr(str2.find(ch) + 1);
//	}
//	return s;
//}
string st[LEN];
int len = 0;
string* split(const string str, const string ch) {
	string str2 = str + ch;//
	while (str2.find(ch) <= str.size()) {
	   // 每次从字符串变量str头部开始剪切到字符变量ch第一次出现的位置
		st[len]=(str2.substr(0, str2.find(ch)));
		//把截取后的剩余的字符串重新复制给str2
		str2 = str2.substr(str2.find(ch) + 1);
		len++;
	}
	len++; //数组长度
	return st;
}

用法:demo.cpp

#include<iostream>
#include "split.h"
int main() {
	//第一个参数是要被分割的字符串,第二个参数分割的字符
	/*vector<string> v = split("asd,qw,e,adsa,145", ",");
	vector<string>::iterator vit = v.begin();
	while (vit != v.end()) {
		cout << *vit << " ";
		vit++;
	}*/
	string *v = split("asd,qw,e,adsa,145",",");
	int i = 0;
	while (i<len) {
		cout << *(v + i) <<" ";
		i++;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值