c++如何实现字符串分割函数split?(代码示例)
导读:收集整理的这篇文章主要介绍了c++如何实现字符串分割函数split?(代码示例),觉得挺不错的,现在分享给大家,也给大家做个参考。在学习c++中string相关基本用法的时候,发现了sstream的istringstream[1]可以将字符...
收集整理的这篇文章主要介绍了c++如何实现字符串分割函数split?(代码示例),觉得挺不错的,现在分享给大家,也给大家做个参考。在学习c++中string相关基本用法的时候,发现了sstream的istringstream[1]可以将字符串类似于控制台的方式进行输入,而实质上这个行为等同于利用空格将一个字符串进行了分割。于是考虑到可以利用这个特性来实现c++库函数中没有的字符串分割函数splIT
string src("Avatar 123 5.2 Titanic K");
istringstream istrStream(src);
//建立src到istrStream的联系string s1, s2;
int n;
double d;
char c;
istrStream >
>
s1 >
>
n >
>
d >
>
s2 >
>
c;
//以空格为分界的各数值则输入到了对应变量上实现细节
目的是可以像js中一样,调用一个函数即可以方便地获取到处理完毕后的字符串数组,根据c++的实际情况再进行参数调整。
1. 输入输出:
string* split(int&
length, string str, const char token = ' ')返回:处理完的字符串数组的首地址
传入:字符串str、分隔符token(默认参数为空格)、以及引用参数length,指明处理完毕后动态分配的数组长度
2. 数据透明处理:
由于istringstream会像cin一样,把空格视为数据间的界限,所以当分隔符不是空格时,需要将传入的分隔符换为空格,并且要提前对原有空格进行数据透明处理
字符替换利用了库algorithm中的replace() [2]
const char SPACE = 0;
if(token!=' ') {
// 先把原有的空格替换为ASCII中的不可见字符 replace(str.begin(), str.end(), ' ', SPACE);
// 再把分隔符换位空格,交给字符串流处理 replace(str.begin(), str.end(), token, ' ');
}
假设输入字符串为:"a b,c,d,e,f g" 分隔符为非空格:',' 则被替换为:"aSPACEb c d e fSPACEg"
3. 数据分割:
//实例化一个字符串输入流,输入参数即待处理字符串 istringstream i_stream(str);
//将length置零 length = 0;
queuestring>
q;
//用一个string实例s接收输入流传入的数据,入队并计数 string s;
while (i_stream>
>
s) {
q.push(s);
length++;
}
4. 数组生成:
//根据计数结果动态开辟一个字符串数组空间 string* results = new string[length];
//将队列中的数据转入数组中 for (int i = 0;
i length;
i++) {
results[i] = q.front();
//将替换掉的空格进行还原 if(token!=' ') replace(results[i].begin(), results[i].end(), SPACE, ' ');
q.pop();
}
完整代码
#include iostream>
#include string>
#include queue>
#include sstream>
#include algorithm>
using namespace std;
string* split(int&
length, string str,const char token = ' ') {
const char SPACE = 0;
if(token!=' ') {
replace(str.begin(), str.end(), ' ', SPACE);
replace(str.begin(), str.end(), token, ' ');
}
istringstream i_stream(str);
queuestring>
q;
length = 0;
string s;
while (i_stream>
>
s) {
q.push(s);
length++;
}
string* results = new string[length];
for (int i = 0;
i length;
i++) {
results[i] = q.front();
q.pop();
if(token!=' ') replace(results[i].begin(), results[i].end(), SPACE, ' ');
}
return results;
}
//测试:int main() {
int length;
string* results = split(length, "a b,c,d,e,f g", ',');
for (int i = 0;
i length;
i++) coutresults[i]endl;
return 0;
}
本文来自 C#.Net教程 栏目,欢迎学习!
以上就是c++如何实现字符串分割函数split?(代码示例)的详细内容,更多请关注其它相关文章!
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c++如何实现字符串分割函数split?(代码示例)
本文地址: https://pptw.com/jishu/593708.html
