C++中, 将字符串按任意空白字符(空格 ' ', 制表符 '\t', 换行符 '\n', 回车符 '\r' 等)分割为子字符串集合。 遍历字符串中的单词可以通过多种方法实现,具体取决于需求和 C++ 版本。

1、使用 std::Springstead 和 operator>>

最简洁且符合 C++ 风格的方式。

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string s = "Somewhere down the road";
    std::istringstream iss(s);
    std::string word;
    while (iss >> word) {
        std::cout << word << std::endl;
    }
    return 0;
}

2、使用 std::getline 和 std::istringstream

如果需要按特定分隔符(如逗号、分号等)分割字符串,可以使用 std::getline

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string s = "word1,word2,word3";
    std::istringstream iss(s);
    std::string word;
    while (std::getline(iss, word, ',')) {
        std::cout << word << std::endl;
    }
    return 0;
}

3、使用 std::ranges(C++20 及以上)

如果编译器支持 C++20 或更高版本,可以使用 std::ranges 来实现更简洁的代码。

#include <iostream>
#include <ranges>
#include <string_view>

int main() {
    std::string_view text = "Lorem ipsum dolor sit amet";
    for (auto word : text | std::views::split(' ')) {
        std::cout << std::string_view{word.begin(), word.end()} << std::endl;
    }
    return 0;
}

4、使用 Boost 库

如使用 Boost 库,可以利用其强大的字符串处理功能,Boost 的 boost::split 函数提供了灵活的分割功能,支持多种分隔符和选项。

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string s = "Somewhere down the road";
    std::vector<std::string> words;
    boost::split(words, s, boost::is_any_of(" "));
    for (const auto& word : words) {
        std::cout << word << std::endl;
    }
    return 0;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表