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++的相关文档或者教程。