按字符拆分字符串

时间:2022-12-30
本文介绍了按字符拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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(),但是由于它不方便(将您的字符串转换为字符数组等)我不喜欢使用它.有没有更简单的方法来实现这一点?

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() 函数.但是,由于它需要 起点 和长度,因此当我想拆分日期时它会失败.因为用户可能将其输入为 7/12/2012 或 07/3/2011,在计算/"分隔符的下一个位置之前,我可以真正知道长度.

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.

#include <string>
#include <vector>
#include <sstream>

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);
}

这会产生与内容相同的向量

Which results in a vector with the same contents as

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

这篇关于按字符拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:需要可预测的随机生成器 下一篇:如何在 Linux 或 Windows 中为 OS X 编译?

相关文章

最新文章