【C++深入浅出】STL之string用法详解
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "str: " << str << std::endl;
// 获取字符串长度
std::cout << "Length of str: " << str.length() << std::endl;
// 字符串连接
std::string str2 = " Welcome to C++!";
str += str2;
std::cout << "str after concatenation: " << str << std::endl;
// 字符串查找
if (str.find("World") != std::string::npos) {
std::cout << "Found \"World\" in str." << std::endl;
}
// 字符串替换
str.replace(str.find("World"), 5, "STL");
std::cout << "str after replacement: " << str << std::endl;
// 字符串子串
std::string substr = str.substr(7, 3);
std::cout << "Extracted substring: " << substr << std::endl;
return 0;
}
这段代码展示了如何在C++中使用std::string
类的基本用法,包括创建字符串、获取字符串长度、字符串连接、字符串查找、字符串替换和字符串子串的提取。
评论已关闭