【问题标题】:how do you split a string embedded in a delimiter in C++?如何拆分嵌入在 C++ 分隔符中的字符串?
【发布时间】:2020-09-14 12:06:42
【问题描述】:

我了解如何在 C++ 中通过分隔符将字符串拆分为字符串,但是如何在分隔符中拆分字符串嵌入,例如尝试将”~!hello~! random junk... ~!world~!” 通过字符串”~!” 拆分为[“hello”, “ random junk...”, “world”] 的数组?是否有任何 C++ 标准库函数可以实现这一点,或者如果没有任何算法可以实现这一点?

【问题讨论】:

  • 不,没有 C++ 库函数或算法可以做到这一点。你只需要自己实现这个简单的算法。
  • 你的预期输出不应该是["hello", " random junk... ", "world"]吗?
  • @goodvibration 我认为 OP 意味着一个令牌被给定的字符串引用。这是一个引号而不是分隔符。
  • @goodvibration,对不起,你是对的
  • 我错过了什么吗?如果你知道如何用分隔符分割,你可以应用它并删除第一个和最后一个空条目,不是吗?

标签: c++ string algorithm split delimiter


【解决方案1】:
#include <iostream>
#include <vector>
using namespace std;

vector<string> split(string s,string delimiter){
    vector<string> res;
    s+=delimiter;       //adding delimiter at end of string
    string word;
    int pos = s.find(delimiter);
    while (pos != string::npos) {
        word = s.substr(0, pos);                // The Word that comes before the delimiter
        res.push_back(word);                    // Push the Word to our Final vector
        s.erase(0, pos + delimiter.length());   // Delete the Delimiter and repeat till end of String to find all words
        pos = s.find(delimiter);                // Update pos to hold position of next Delimiter in our String 
    }   
    res.push_back(s);                          //push the last word that comes after the delimiter
    return res;
}

int main() {
        string s="~!hello~!random junk... ~!world~!";
        vector<string>words = split(s,"~!");
        int n=words.size();
        for(int i=0;i<n;i++)
            std::cout<<words[i]<<std::endl;
        return 0;
 }

上述程序将查找所有出现在您指定的分隔符之前、中间和之后的单词。通过对函数进行微小的更改,您可以使函数适合您的需要(例如,如果您不需要查找出现在第一个分隔符或最后一个分隔符之前的单词)。

但是根据您的需要,给定的函数会根据您提供的分隔符以正确的方式进行分词

我希望这能解决你的问题!

【讨论】:

  • 一个小注意事项 - 如果你不想要长度为 0 的单词,在将其推送到向量之前,将以下检查条件添加到上面的拆分函数中 - if(word.length()!=0)。这将确保只有 非空的单词会被添加到最终向量中
猜你喜欢
  • 1970-01-01
  • 2010-11-10
  • 2012-03-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多