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