概述
在学习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;
queue<string> 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);
queue<string> 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++) cout<<results[i]<<endl;
return 0;
}
登录后复制
本文来自 C#.Net教程 栏目,欢迎学习!
以上就是c++如何实现字符串分割函数split?(代码示例)的详细内容,更多请关注靠谱客其它相关文章!
最后
以上就是优雅网络为你收集整理的c++如何实现字符串分割函数split?(代码示例)的全部内容,希望文章能够帮你解决c++如何实现字符串分割函数split?(代码示例)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复