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)等。