关于string的各种函数的介绍就不多说了,网上到处都有,当然我不是说我写的这个网上没有,但是绝对原创,以下结合代码说明吧:
/*
* strtoken.h
*
* Created on:
* Author: wdmcel
*/
#ifndef STRTOKEN_H_
#define STRTOKEN_H_
#include <vector>
#include <string.h>
#include <iostream>
using namespace std;
void string_token(string& instr_, char ch_, vector<string>& outstr_) //对string类型的字符串分割
{
string instr(1, ch_);
//cout << instr << endl;
instr += instr_;
instr.append(1, ch_);
string str_tmp;
int current, start, mount;
int first = instr.find_first_of(ch_, 0); //从下标0开始找到ch_第一次出现的位置
current = first;
int last = instr.find(ch_, current + 1); //找下一个ch_出现的位置
while (-1 != last) //循环处理每两个ch_之间的字符子串
{
start = current + 1;
mount = last - current - 1;
if(mount > 0)
{
str_tmp.assign(instr, start, mount); //将instr从start开始的mount个字符分配给str_tmp
outstr_.push_back(str_tmp); //将分割的子串保存在一个vector中
}
current = last;
last = instr.find(ch_, current + 1);
}
}
void string_token(char* str_, char ch_, vector<string>& outstr_) //对c风格的字符串分割
{
string instr(str_); //调用string构造函数,将str_转换为 string类型
string_token(instr, ch_, outstr_); //调用上述函数
}
#endif /* STRTOKEN_H_ */
测试代码:
/* * main.cpp * * Created on: * Author: wdmcel */ #include "strtoken.h" template<typename T> void print_vector(const vector<T>& v) { cout << "The result is :" << endl; for (unsigned int i=0; i<v.size(); ++i) { cout << v[i] <<endl; } } int main() { string data_str("abcde*cdefgh*sldfkslkf*slkf"); vector<string> test_str; char data_char = 'f'; char* data_pchar = "abc#cde#wdm#yong#adf"; char data_test = '#'; vector<string> test_pchar; string_token(data_str, data_char, test_str); cout << data_str << "\t" << data_char << endl; if (test_str.size() > 0) { print_vector(test_str); } string_token(data_pchar, data_test, test_pchar); cout << data_pchar << "\t" << data_test << endl; if (test_pchar.size() > 0) { print_vector(test_pchar); } //system("pause"); return 0; } 测试部分就不多解释了。
其实,关于STL中封装好的类而言,都是对其中的函数详加理解,并调用之,本文所用函数其实不多,仅append,find,find_first_of等几个而已。