65.9K
CodeProject 正在变化。 阅读更多。
Home

STL 分隔字符串函数

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.60/5 (7投票s)

2007年4月8日

公共领域
viewsIcon

75853

使用单个字符分隔符分割字符串。模板函数。

引言

使用给定分隔符分割字符串是一项非常常见的操作。
不幸的是,STL 没有提供任何直接的方法来实现这一点。
此分割实现是模板化的,并使用类型推导来确定作为参数传递的字符串和容器的类型,这些类型必须是某种形式的 basic_string<> 和任何实现 push_back() 方法的容器。

您可以将此代码直接放置在使用的文件中,或者为它创建一个单独的包含文件。

请注意,字符串类型并未完全指定,允许特性和分配器采用默认值。
在某些情况下,这可能不是您想要的,并且某些编译器可能不喜欢它。

背景

我写这个是因为我发现 Paul J. Weiss 编写的标题为 STL Split String 的代码比我需要的更复杂,对于这个常见的简单情况而言。

最常见的情况应该编写起来最容易。

源代码

template <typename E, typename C>
size_t split(std::basic_string<E> const& s,
             C &container,
             E const delimiter,
             bool keepBlankFields = true)
{
    size_t n = 0;
    std::basic_string<E>::const_iterator it = s.begin(), end = s.end(), first;
    for (first = it; it != end; ++it)
    {
        // Examine each character and if it matches the delimiter
        if (delimiter == *it)
        {
            if (keepBlankFields || first != it)
            {
                // extract the current field from the string and
                // append the current field to the given container
                container.push_back(std::basic_string<E>(first, it));
                ++n;
                
                // skip the delimiter
                first = it + 1;
            }
            else
            {
                ++first;
            }
        }
    }
    if (keepBlankFields || first != it)
    {
        // extract the last field from the string and
        // append the last field to the given container
        container.push_back(std::basic_string<E>(first, it));
        ++n;
    }
    return n;
}

示例用法

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

std::string tests[3] = {
    std::string(""),
    std::string("||three||five|"),
    std::string("|two|three||five|")
};

char* delimiter = "|";

for (int i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i)
{
    std::vector< std::basic_string<char> > x;
    size_t n = split(tests[i], x, delimiter[0], true);
    std::cout << n << "==" << x.size() << " fields" << std::endl;
    if (n)
    {
        std::copy(x.begin(), x.end(),
            std::ostream_iterator<std::string>(std::cout, delimiter));
        std::cout << std::endl;
    }
}
© . All rights reserved.