C++ 实现 split 操作
理由:由于 C++ 标准库里面没有字符分割函数 split ,这可太不方便了,我们利用 STL 来实现自己的 split 函数:
原型:vector<string> split(const string& s, const string& seperator);
1 // codeThinking.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <windows.h> 6 #include <iostream> 7 #include <vector> 8 #include <stack> 9 #include <cstring> 10 #include<unordered_map> 11 12 using namespace std; 13 14 vector<string> split(const string& s, const string& seperator) { 15 vector<string> result; 16 unsigned int posBegin = 0; 17 unsigned int posSeperator = s.find(seperator); 18 19 while (posSeperator != s.npos) { 20 result.push_back(s.substr(posBegin, posSeperator - posBegin));// 21 posBegin = posSeperator + seperator.size(); // 分隔符的下一个元素 22 posSeperator = s.find(seperator, posBegin); 23 } 24 if (posBegin != s.length()) // 指向最后一个元素,加进来 25 result.push_back(s.substr(posBegin)); 26 27 return result; 28 } 29 30 void splitTest(const string& str,string& symbol) { 31 vector<string> result; 32 result = split(str, symbol); 33 for (int i = 0; i < result.size(); ++i) { 34 cout <<atoi(result[i].c_str())<< endl; // 把数字字符串转换为 数字 35 } 36 } 37 38 int _tmain(int argc, _TCHAR* argv[]) 39 { 40 string widths = "5 5 5 5 5 5 10 10 10 10 10 10 10 10 10 10 10 10 5 5 5 5 5 5 5 5"; 41 string symbol = " "; 42 43 splitTest(widths,symbol); 44 45 46 system("pause"); 47 return 0; 48 }
所有博文均为原著,如若转载,请注明出处!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗