C++中String类的字符串分割实现
最近笔试,经常遇到需要对字符串进行快速分割的情景,主要是在处理输入的时候,而以前练习算法题或笔试,很多时候不用花啥时间考虑测试用例输入的问题。可是C++标准库里面没有像java的String类中提供的字符分割函数split ,着实不方便。那么怎么解决这个问题呢?整理了一些方法如下:
1.简洁高效的方法(不过只能包含一个分隔符):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <vector> #include <string> #include <iostream> using namespace std; void SplitString( const string& s, vector<string>& v, const string& c) { string::size_type pos1, pos2; pos2 = s.find(c); pos1 = 0; while (string::npos != pos2) { v.push_back(s.substr(pos1, pos2-pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if (pos1 != s.length()) v.push_back(s.substr(pos1)); } int main(){ string s = "a,b,c,d,e,f" ; vector<string> v; SplitString(s, v, "," ); //可按多个字符来分隔; for (vector<string>::size_type i = 0; i != v.size(); ++i) cout << v[i] << " " ; cout << endl; //输出: a b c d e f } |
当处理有空格的字符串时,还是很有用的!!
1 | 使用 void SplitString( const string& s, vector<string>& v, const string& c),和将v作为返回值都是可以的!<br><br> |
2.可包含多个分隔符的实现方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <vector> #include <string> #include <iostream> using namespace std; vector<string> split( const string &s, const string &seperator){ vector<string> result; typedef string::size_type string_size; string_size i = 0; while (i != s.size()){ //找到字符串中首个不等于分隔符的字母; int flag = 0; while (i != s.size() && flag == 0){ flag = 1; for (string_size x = 0; x < seperator.size(); ++x) if (s[i] == seperator[x]){ ++i; flag = 0; break ; } } //找到又一个分隔符,将两个分隔符之间的字符串取出; flag = 0; string_size j = i; while (j != s.size() && flag == 0){ for (string_size x = 0; x < seperator.size(); ++x) if (s[j] == seperator[x]){ flag = 1; break ; } if (flag == 0) ++j; } if (i != j){ result.push_back(s.substr(i, j-i)); i = j; } } return result; } int main(){ // string s = "a,b*c*d,e"; string s; getline(cin,s); vector<string> v = split(s, ",*" ); //可按多个字符来分隔; for (vector<string>::size_type i = 0; i != v.size(); ++i) cout << v[i] << " " ; cout << endl; //输出: a b c d e } |
方法三:用C语言中的strtok 函数来进行分割
原型: char *strtok(char *str, const char *delim);strtok函数包含在头文件<string.h>中,对于字符数组可以采用这种方法处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <string.h> #include <stdio.h> int main(){ char s[] = "a,b*c,d" ; const char *sep = ",*" ; //可按多个字符来分割 char *p; p = strtok (s, sep); while (p){ printf ( "%s " , p); p = strtok (NULL, sep); } printf ( "\n" ); return 0; } //输出: a b c d |
朱颜辞镜花辞树,敏捷开发靠得住!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了