按字符拆分字符串

新手上路,请多包涵

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

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

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

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

原文由 Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 608
2 个回答

使用向量、字符串和字符串流。有点麻烦,但可以解决问题。

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

这会产生一个与以下内容相同的向量

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

原文由 thelazydeveloper 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是在 C++ 中拆分字符串的另一种方法,在这种情况下使用 wstring 并且仅使用 find 和 substr 函数。

 #include <iostream>
#include <vector>

std::vector<std::wstring> SplitWstring(const std::wstring& text, const std::wstring& subText)
{
    std::vector<std::wstring> result;
    size_t left = 0;
    size_t right = text.find(subText);
    size_t textSize = text.size();
    size_t subTextSize = subText.size();

    while (right != std::wstring::npos)
    {
        if (right > left)
        {
            size_t size = right - left;
            result.push_back(text.substr(left, size));
            left = right + subTextSize;
        }
        else
            left += subTextSize;

        right = text.find(subText, left);
    }

    if (left < textSize)
        result.push_back(text.substr(left));

    return result;
}

int main()
{
    //std::wstring text = L"";                          // Result: {}
    //std::wstring text = L"-";                         // Result: {"-"}
    //std::wstring text = L"ONE";                       // Result: {"ONE"}
    //std::wstring text = L"ONE---TWO---THREE";         // Result: {"ONE", "TWO", "THREE"}
    std::wstring text = L"---ONE---TWO---THREE---";     // Result: {"ONE", "TWO", "THREE"}
    std::wstring subText = L"---";
    std::vector<std::wstring> splitted = SplitWstring(text, subText);

    if (splitted.size() > 0)
        return 1;

    return 0;
}

原文由 Juan Carlos 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题