C++中format函数与字符串分割

发布时间:2024-10-11 10:16:35 作者:小樊
来源:亿速云 阅读:78

在 C++ 中,可以使用 std::string 类的成员函数 findsubstr 来实现字符串分割。下面是一个示例代码:

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

std::vector<std::string> split(const std::string& str, char delim) {
    std::vector<std::string> tokens;
    std::size_t start = 0, end = str.find(delim);

    while (end != std::string::npos) {
        tokens.push_back(str.substr(start, end - start));
        start = end + 1;
        end = str.find(delim, start);
    }

    tokens.push_back(str.substr(start));
    return tokens;
}

int main() {
    std::string str = "C++ is a powerful programming language.";
    char delim = ' ';

    std::vector<std::string> tokens = split(str, delim);

    for (const auto& token : tokens) {
        std::cout << token << std::endl;
    }

    return 0;
}

在上面的示例中,split 函数接受一个字符串和一个分隔符作为参数,并返回一个包含分割后的子字符串的 std::vector 对象。该函数使用 find 函数查找分隔符的位置,并使用 substr 函数提取子字符串。然后,该函数将子字符串添加到 tokens 向量中,并继续查找下一个分隔符,直到找不到分隔符为止。最后,该函数将最后一个子字符串添加到 tokens 向量中,并返回该向量。

main 函数中,我们定义了一个字符串和一个分隔符,并调用 split 函数来分割字符串。然后,我们遍历 tokens 向量并打印每个子字符串。

推荐阅读:
  1. go语言相对于c/c++的优势有哪些
  2. 怎么在C++中将结构体与Json字符串进行转换

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++ format函数在跨平台开发中的表现

下一篇:C++ format函数在性能优化中的角色

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》