c++ - 如何在 C++ 中标记字符串?

标签 c++ string split tokenize

Java有一个方便的split方法:

String str = "The quick brown fox";
String[] results = str.split(" ");

在 C++ 中有没有一种简单的方法可以做到这一点?

最佳答案

Boost tokenizer类可以使这类事情变得非常简单:

#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main(int, char**)
{
    string text = "token, test   string";

    char_separator<char> sep(", ");
    tokenizer< char_separator<char> > tokens(text, sep);
    BOOST_FOREACH (const string& t, tokens) {
        cout << t << "." << endl;
    }
}

针对 C++11 更新:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main(int, char**)
{
    string text = "token, test   string";

    char_separator<char> sep(", ");
    tokenizer<char_separator<char>> tokens(text, sep);
    for (const auto& t : tokens) {
        cout << t << "." << endl;
    }
}

关于c++ - 如何在 C++ 中标记字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5751031/

相关文章:

c++ - 抽象工厂模式客户端代码

c++ - 如何在我的 C++ 代码中避免此类内存泄漏?

c++ - 在 C MexFunction 中使用 Besselk 函数

java - 为什么 String.split ("£", 2) 不工作?

Java 在逗号 (,) 上拆分字符串,括号 () 之间除外

c++ - 指向结构体指针数组的指针

java - 将字符串转换为整数并在 Java 中添加它们

java - 在字符串中查找子字符串的位置(不是 indexOf)

regex - 使用正则表达式将相同数量的重复字符替换为其他字符

ios - 根据 NSDictionary 键值将 NSArray 拆分为子数组