在C++中,可以使用string
和stringstream
来处理字符串。
string
类来创建和操作字符串:#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 获取字符串长度
std::cout << "Length: " << str.length() << std::endl;
// 获取子字符串
std::string subStr = str.substr(0, 5);
std::cout << "Substring: " << subStr << std::endl;
// 连接字符串
std::string concatStr = str + " Welcome!";
std::cout << "Concatenated string: " << concatStr << std::endl;
// 查找字符串
std::size_t found = str.find("World");
if (found != std::string::npos) {
std::cout << "Found at index: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
stringstream
类来处理字符串流:#include <iostream>
#include <sstream>
int main() {
std::string str = "42 3.14 Hello";
std::istringstream iss(str); // 从字符串创建输入流
int num;
float fNum;
std::string word;
// 从流中提取数据
iss >> num >> fNum >> word;
std::cout << "Number: " << num << std::endl;
std::cout << "Float Number: " << fNum << std::endl;
std::cout << "Word: " << word << std::endl;
std::ostringstream oss; // 创建输出流
oss << "Concatenated: " << num << " " << fNum << " " << word;
std::cout << oss.str() << std::endl; // 输出流中的字符串
return 0;
}
这是一些简单的示例,string
和stringstream
类还有更多的功能和用法,可以根据具体需求查阅C++文档来了解更多信息。