C ++:一个字符分割字符串 [英] C++: Splitting a string by a character

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

问题描述

我知道这是一个很简单的问题,但我只是想解决它自己一劳永逸

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()中,但由于它的不便之处(将你的字符串为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);
}

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

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