求字符串分解(C++)

xlttap 2009-08-04 06:56:47
假如有一字符串:
string s = "##,sd###,,,##jk<sd##,,,<<";
string delim = "#,<";
请问如何按delim来分割字符串s?请给出一个函数split(string s, const string &delim)
也就是要得到结果是:
sd
jk
sd
我自己写的在测试的时候有问题。所以请大家帮写一个。如果找我程序的问题,我还是觉得大家写一个更快。
...全文
116 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
xlttap 2009-08-04
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 baihacker 的回复:]
C/C++ code#include<iostream>
#include<cstdlib>
#include<string>usingnamespace std;int main()
{string str="##,sd###,,,##jk <sd##,,, < <";string delim="#, <";char buff[256];
strcpy(buff, str.c_str()¡­
[/Quote]

谢谢啊。我一直不太习惯用C的库函数。因为我是从java转过来做C++的。呵呵。
xlttap 2009-08-04
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 superspring 的回复:]
用 boost的split
[/Quote]

如果用??我没有用过,给个例子吧。
xlttap 2009-08-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 qqiuzaihui 的回复:]
C++中不是也自带了split函数么?
下面是C#代码, 供你参考:

C# codestring s="##,sd###,,,##jk <sd##,,, < <";char[] delim= {'#',',','<' };string[] ss= s.Split(delim);for (int i=0; i< ss.Length; i++)
{if (ss[i]!="")
{
Console.WriteLine(ss[i].ToString());
}
}
[/Quote]

我要的是ss= s.Split(delim)中Split的源码;你这样写,我java里早就会了。
baihacker 2009-08-04
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;


int main()
{
string str = "##,sd###,,,##jk <sd##,,, < <";
string delim = "#, <";
char buff[256];
strcpy(buff, str.c_str());
char* result = strtok(buff, delim.c_str());
for (;result;result = strtok(NULL, delim.c_str())) puts(result);
return 0;
}
superspring 2009-08-04
  • 打赏
  • 举报
回复
用 boost的split
baihacker 2009-08-04
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstdlib>
using namespace std;


int main()
{
char str[] = "##,sd###,,,##jk <sd##,,, < <";
char* result = strtok(str, "#, <");
for (;result;result = strtok(NULL, "#, <")) puts(result);
return 0;
}
qqiuzaihui 2009-08-04
  • 打赏
  • 举报
回复
C++中不是也自带了split函数么?
下面是C#代码, 供你参考:


string s = "##,sd###,,,##jk <sd##,,, < <";
char[] delim = { '#', ',', '<' };

string[] ss = s.Split(delim);
for (int i = 0; i < ss.Length; i++)
{
if (ss[i] != "")
{
Console.WriteLine(ss[i].ToString());
}
}
Aeris 2009-08-04
  • 打赏
  • 举报
回复
Boost库中的String Algorithm里面就有split算法,可以试试。

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧