string和stringstream是C++標準庫中的兩個類,用于處理字符串。
常用的string類方法有:
示例代碼:
#include <string>
#include <iostream>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
std::string str3;
str3 = str1 + " " + str2;
std::cout << str3 << std::endl;
if (str1 == "hello") {
std::cout << "str1 is equal to hello" << std::endl;
}
std::cout << "Substring: " << str3.substr(6, 5) << std::endl;
str3.insert(5, " C++");
std::cout << "After insertion: " << str3 << std::endl;
str3.erase(11, 5);
std::cout << "After deletion: " << str3 << std::endl;
return 0;
}
常用的stringstream類方法有:
示例代碼:
#include <iostream>
#include <sstream>
int main() {
std::string str = "12345";
int num;
std::stringstream ss;
ss << str; // 將字符串寫入stringstream對象
ss >> num; // 從stringstream對象讀取數據
std::cout << "Number: " << num << std::endl;
ss.str(""); // 清空stringstream對象的內容
ss << "3.14";
float f;
ss >> f;
std::cout << "Float: " << f << std::endl;
return 0;
}
以上是string和stringstream類的簡單用法介紹,更詳細的用法可以參考C++的相關文檔或者教程。