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