用字符分割字符串 [英] Splitting a string by a character

查看:107
本文介绍了用字符分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个非常简单的问题,但我只是想一劳永逸地解决它

I know this is a quite easy problem but I just want to solve it for myself once and for all

我只想将字符串拆分成一个数组使用字符作为分割定界符。 (很像C#著名的 .Split()函数。我当然可以应用蛮力方法,但是我想知道是否还有什么比这更好的方法。

I would simply like to split a string into an array using a character as the split delimiter. (Much like the C#'s famous .Split() function. I can of course apply the brute-force approach but I wonder if there anything better than that.

到目前为止,我已经搜索过,也许最接近的解决方法是使用 strtok(),但是由于这样做不方便(将您的字符串转换为a char数组等。)我不喜欢使用它。有没有更简单的方法来实现它?

So far the I've searched and probably the closest solution approach is the usage of strtok(), however due to it's inconvenience(converting your string to a char array etc.) I do not like using it. Is there any easier way to implement this?

注意:我想强调一下因为人们可能会问为什么蛮力不起作用。我的蛮力解决方案是创建一个循环,并在其中使用 substr()函数,但是由于需要起点和长度,当我想分割日期时,它会失败,因为用户可能会在2012年7月12日或2011年7月3日输入日期,因此我可以在计算下一个日期之前真正知道长度 /定界符的位置。

Note: I wanted to emphasize this because people might ask "How come brute-force doesn't work". My brute-force solution was to create a loop, and use the substr() function inside. However since it requires the starting point and the length, it fails when I want to split a date. Because user might enter it as 7/12/2012 or 07/3/2011, where I can really tell the length before calculating the next location of '/' delimiter.

推荐答案

使用向量,字符串和字符串流。虽然有点麻烦,但它确实

Using vectors, strings and stringstream. A tad cumbersome but it does the trick.

std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<std::string> seglist;

while(std::getline(test, segment, '_'))
{
   seglist.push_back(segment);
}

哪个向量的内容与

std::vector<std::string> seglist{ "this", "is", "a", "test", "string" };

这篇关于用字符分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆