使用标准库替换strtok循环

Les*_*ite 5 c++ stl

我有一个strtok解决的问题(从字符串中拆分子串)但我意识到strtok不安全.我想使用C++标准库的一些更现代的部分.

我应该用什么呢?

static int ParseLine(std::string line, 
                     std::string seps, 
                     int startIdx, 
                     std::vector<CNode>& collection)
{
    if (startIdx > collection.size())
    {
        throw std::invalid_argument("the start index is out of range");
    }
    char buf[2000];
    strcpy_s(buf, line.c_str());
    auto idx = startIdx;
    for (auto objectType = strtok(buf, seps.c_str()); objectType != nullptr; idx++)
    {
        if (idx == collection.size())
        {
            collection.push_back(CNode(idx));
        }
        collection[idx].SetObjectType(objectType);
        objectType = strtok(nullptr, seps.c_str());
    }
    return (idx - 1);
}
Run Code Online (Sandbox Code Playgroud)

这里是一个用_CRT_SECURE_NO_WARNINGS编译的完整示例:

#include <string>
#include <vector>
#include <iostream>

class CObject
{
    std::string _objectType;

public:
                CObject() : _objectType("n/a") {}
    void        SetObjectType(std::string objectType) { _objectType = objectType; }
    std::string GetObjectType() const { return _objectType; }

};

class CNode
{
    int     _id;
    CObject _object;

public:
    explicit CNode(int id) : _id(id) {}
    void        SetObjectType(std::string objectType) { _object.SetObjectType(objectType); }
    std::string GetObjectType() const { return _object.GetObjectType(); }

};

// Update the collection of nodes with the object types found in the line specified.
// Return the number of elements in the collection.
static int ParseLine(std::string line, std::string seps, int startIdx, std::vector<CNode>& collection)
{
    if (startIdx > collection.size())
    {
        throw std::invalid_argument("the start index is out of range");
    }
    char buf[2000];
    strcpy_s(buf, line.c_str());
    auto idx = startIdx;
    for (auto objectType = strtok(buf, seps.c_str()); objectType != nullptr; idx++)
    {
        if (idx == collection.size())
        {
            collection.push_back(CNode(idx));
        }
        collection[idx].SetObjectType(objectType);
        objectType = strtok(nullptr, seps.c_str());
    }
    return (idx - 1);
}

int main()
{
    std::string seps = ".";
    //                   2   3   4   5   6   7   8   9
    std::string line = "abc.def.ghi.klm.nop.qrs.tuv.wxyz";
    std::vector<CNode> collection { CNode(0), CNode(1), CNode(2) , CNode(3) , CNode(4) , CNode(5) };
    auto startAt = 2;
    try
    {
        auto collection_size = ParseLine(line, seps, startAt, collection);
        std::cout << collection_size << std::endl;
        for (auto value : collection)
        {
            std::cout << value.GetObjectType() << std::endl;
        }
    }
    catch (std::invalid_argument& e)
    {
        std::cout << " out of range exception " << e.what() << std::endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*les 3

以下是拆分分隔字符串的两个示例。

第一个std::getline与字符串流一起使用,指定分隔符而不是使用默认的换行符。此技术只能使用单字符分隔符。

第二个示例使用该<regex>库,它允许任意长度的分隔符,并且还使您可以更好地控制分隔符的识别方式。请注意,点字符必须在正则表达式规范中转义,因为在正则表达式语言中,“.” 充当通配符。

#include <iostream>
#include <sstream>
#include <vector>
#include <regex>

std::vector<std::string> GetlineSplit(std::string const& line) {
    static const char sep = '.';
    std::istringstream liness{line};
    std::vector<std::string> fields;
    for(std::string field; std::getline(liness, field, sep); ) {
        fields.push_back(field);
    }
    return fields;
}

std::vector<std::string> RegexSplit(std::string const& line) {
    std::regex seps("\\."); // the dot character needs to be escaped in a regex
    std::sregex_token_iterator rit(line.begin(), line.end(), seps, -1);
    return std::vector<std::string>(rit, std::sregex_token_iterator());
}

int main() {
    std::string line = "abc.def.ghi.klm.nop.qrs.tuv.wxyz";

    std::cout << "getline split result:\n";
    auto fields_getline = GetlineSplit(line);
    for(const auto& field : fields_getline) {
        std::cout << field << '\n';
    }

    std::cout << "\nregex split result:\n";
    auto fields_regex = RegexSplit(line);
    for(const auto& field : fields_regex) {
        std::cout << field << '\n';
    }
}
Run Code Online (Sandbox Code Playgroud)