阅读量:0
std::stringstream
是 C++ 标准库中的一个类,它位于 <sstream>
头文件中。std::stringstream
可以方便地处理字符串和数字之间的转换,以及对字符串进行拼接、分割等操作。
下面是一些使用 std::stringstream
进行字符串操作的例子:
1. 将数字转换为字符串
#include<iostream> #include <sstream> #include<string> int main() { int num = 42; std::stringstream ss; ss<< num; std::string result; ss >> result; std::cout << "Number as string: "<< result<< std::endl; return 0; }
2. 将字符串转换为数字
#include<iostream> #include <sstream> #include<string> int main() { std::string str_num = "42"; std::stringstream ss; ss<< str_num; int result; ss >> result; std::cout << "String as number: "<< result<< std::endl; return 0; }
3. 拼接字符串
#include<iostream> #include <sstream> #include<string> int main() { std::string str1 = "Hello"; std::string str2 = "World"; std::stringstream ss; ss<< str1 << " "<< str2; std::string result; ss >> result; std::cout << "Concatenated string: "<< result<< std::endl; return 0; }
4. 分割字符串
#include<iostream> #include <sstream> #include<string> int main() { std::string input = "Hello World"; std::stringstream ss(input); std::string word1, word2; ss >> word1 >> word2; std::cout << "First word: "<< word1 << ", Second word: "<< word2<< std::endl; return 0; }
这些例子展示了如何使用 std::stringstream
进行基本的字符串操作。你可以根据需要进行更复杂的操作,比如格式化输出、处理逗号分隔的值(CSV)等。