温馨提示×

温馨提示×

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

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

C++编程:tostring与字符串分割

发布时间:2024-09-08 18:55:36 来源:亿速云 阅读:84 作者:小樊 栏目:编程语言

在 C++ 中,std::to_string() 函数用于将数字转换为字符串,而字符串分割可以通过使用 std::string 类的成员函数 substr()find() 来实现

1. 使用 std::to_string() 将数字转换为字符串

#include<iostream>
#include<string>

int main() {
    int num = 42;
    std::string str_num = std::to_string(num);
    std::cout << "Number as string: "<< str_num<< std::endl;
    return 0;
}

2. 使用 substr()find() 分割字符串

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

// 使用指定的分隔符将字符串分割为多个子字符串
std::vector<std::string> split(const std::string& input, char delimiter) {
    std::istringstream iss(input);
    std::vector<std::string> tokens;
    std::string token;

    while (std::getline(iss, token, delimiter)) {
        tokens.push_back(token);
    }

    return tokens;
}

int main() {
    std::string input = "Hello,World,This,Is,A,Test";
    char delimiter = ',';

    std::vector<std::string> tokens = split(input, delimiter);

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

    return 0;
}

这个示例中的 split() 函数接受一个输入字符串和一个分隔符作为参数。它使用 std::istringstreamstd::getline() 函数从输入字符串中读取子字符串,并将它们存储在一个 std::vector<std::string> 容器中。最后,该示例打印出分割后的子字符串。

向AI问一下细节

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

c++
AI