温馨提示×

温馨提示×

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

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

C++ format函数与字符串分割和合并

发布时间:2024-10-11 11:02:36 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在 C++ 中,可以使用 <sstream> 库中的 stringstream 类来实现字符串的格式化、分割和合并。

  1. 字符串格式化

使用 stringstream 类的 str() 成员函数可以将其他类型的数据转换为字符串类型。例如:

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    int age = 25;
    string name = "Tom";
    stringstream ss;
    ss << "My name is " << name << " and I am " << age << " years old.";
    string str = ss.str();
    cout << str << endl;
    return 0;
}

输出结果为:

My name is Tom and I am 25 years old.
  1. 字符串分割

使用 stringstream 类的 >> 操作符可以将字符串按照指定的分隔符进行分割。例如:

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main() {
    string str = "apple,banana,orange";
    stringstream ss(str);
    string item;
    vector<string> items;
    while (getline(ss, item, ',')) {
        items.push_back(item);
    }
    for (const auto& i : items) {
        cout<< i << endl;
    }
    return 0;
}

输出结果为:

apple
banana
orange
  1. 字符串合并

使用 stringstream 类的 << 操作符可以将多个字符串按照指定的分隔符进行合并。例如:

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = "world!";
    stringstream ss;
    ss << str1 << " " << str2;
    string str = ss.str();
    cout << str << endl;
    return 0;
}

输出结果为:

Hello world!
向AI问一下细节

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

c++
AI