std::stringstream(C++字符串操作)

博客介绍了C++标准库中用于字符串输入输出操作的类,重点提及字符串拼接。还介绍了std::setw(8)设置输出宽度为8个字符,不足时用空格填充;std::setfill('0')设置填充字符为 '0',不足时用 '0' 填充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录

std::stringstream是C++标准库中的一个类,用于对字符串进行输入输出操作。

头文件:#include <sstream>

字符串拼接 <<

		int year = 2023, month = 3, day = 4, hour = 13, minute = 45, second = 0;
		std::stringstream ss;
    	ss << std::setfill('0') << std::setw(4) << year << "-"
        << std::setw(2) << month << "-" << std::setw(2) << day
        << " " << std::setw(2) << hour << ":" << std::setw(2) << minute
        << ":" << std::setw(2) << second;
	
		将几个int 转为标准时间格式的字符串:2023-03-04 13:45:00
  • std::setw(8)设置了输出宽度为8个字符。这意味着当要输出的数据不足8个字符宽度时,将使用空格字符填充剩余的空白位置。
  • std::setfill(‘0’) 设置了填充字符为 ‘0’。这意味着,如果要输出的数据不足的字符宽度,将使用填充字符 ‘0’ 来填充剩余的空白位置。
C++ 中,`std::stringstream` 是一个非常强大的工具,可以用于字符串的流式处理,包括将字符串按特定分隔符分割为多个部分。这种技术在处理字符串解析任务时非常常见,例如读取 CSV 数据、解析日志行等。 ### 3.1 使用 `std::getline` 进行自定义分隔符分割 `std::stringstream` 可以与 `std::getline` 结合使用,以指定的分隔符来分割字符串。这种方法适用于任意字符作为分隔符的情况,例如逗号、冒号等。 ```cpp #include <iostream> #include <sstream> #include <string> #include <vector> int main() { std::string input = "apple,banana,orange"; std::stringstream ss(input); std::string token; std::vector<std::string> tokens; while (std::getline(ss, token, ',')) { tokens.push_back(token); } for (const auto& t : tokens) { std::cout << t << std::endl; } } ``` 该方法的优势在于灵活性,允许使用任意字符作为分隔符,并且可以轻松处理多段字符串输入[^2]。 ### 3.2 使用 `operator>>` 进行默认空白字符分割 如果字符串中的分隔符是空格、制表符或换行符,可以直接使用 `operator>>` 来逐个提取单词。这种方式更加简洁,适合处理以空白字符分隔的数据。 ```cpp #include <iostream> #include <sstream> #include <string> int main() { std::string input = "this apple is sweet"; std::stringstream ss(input); std::string word; while (ss >> word) { std::cout << word << std::endl; } } ``` 此方法在处理标准输入或格式良好的文本数据时非常高效,但不适用于非空白分隔符的情况[^4]。 ### 3.3 使用 `std::istringstream` 提高可读性 虽然 `std::stringstream` 可以完成所有任务,但在仅需要输入操作时,使用 `std::istringstream` 能使代码更清晰、意图更明确。 ```cpp #include <iostream> #include <sstream> #include <string> int main() { std::string input = "i am a boy"; std::istringstream iss(input); std::string word; while (iss >> word) { std::cout << word << std::endl; } } ``` 这种方式特别适合仅涉及字符串输入解析的场景,使代码更具可读性和可维护性[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值