使用sstream库处理字符串流

sstream 提供了一系列类,用于字符串流操作。常用的类包括:

  • std::istringstream: 用于从字符串读取数据(输入流)。
  • std::ostringstream: 用于向字符串写入数据(输出流)。
  • std::stringstream: 既可以用于从字符串读取数据,也可以用于向字符串写入数据(双向流)。

下面是如何使用这些类的一些示例。

1、基本用法

std::istringstream

用于从字符串中提取数据。

示例
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string str = "123 456 789";
    std::istringstream iss(str);

    int a, b, c;
    iss >> a >> b >> c;

    std::cout << "a: " << a << ", b: " << b << ", c: " << c << std::endl;
    return 0;
}

std::ostringstream

用于将数据写入字符串。

示例
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::ostringstream oss;
    oss << "Hello, " << "world!" << " " << 123;

    std::string str = oss.str();
    std::cout << str << std::endl; // 输出 "Hello, world! 123"
    return 0;
}

std::stringstream

可以同时读取和写入字符串。

示例
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::stringstream ss;
    ss << "Hello, " << "world!" << " " << 123;

    std::string str = ss.str();
    std::cout << str << std::endl; // 输出 "Hello, world! 123"

    int number;
    ss >> str >> str >> number; // 重用 ss 从头开始读取
    std::cout << "number: " << number << std::endl; // 输出 123
    return 0;
}

2、使用 std::istringstreamstd::getline 切分字符串

你可以使用 std::istringstreamstd::getline 结合使用,按行或者特定分隔符切分字符串。

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

std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::istringstream iss(str);
    std::string token;
    while (std::getline(iss, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

int main() {
    std::string str = "apple,banana,cherry";
    std::vector<std::string> fruits = split(str, ',');

    for (const auto& fruit : fruits) {
        std::cout << fruit << std::endl; // 输出每个单词
    }
    return 0;
}

3、使用 std::ostringstream 拼接字符串

std::ostringstream 可以用于方便地拼接字符串。

示例
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::ostringstream oss;
    oss << "The quick brown fox " << "jumps over " << "the lazy dog.";

    std::string sentence = oss.str();
    std::cout << sentence << std::endl; // 输出 "The quick brown fox jumps over the lazy dog."
    return 0;
}

这些示例展示了 sstream 头文件中的类如何用于处理字符串流,包括读取、写入和切分字符串等操作。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值