#include <iostream>
#include <string>
using namespace std;
int main() {
// 创建字符串对象
string str1 = "Hello, ";
string str2 = "World!";
// 字符串连接
string str3 = str1 + str2;
cout << "str3: " << str3 << endl; // 输出: str3: Hello, World!
// 获取字符串长度
int len = str3.length();
cout << "Length of str3: " << len << endl; // 输出: Length of str3: 13
// 查找子字符串的位置
size_t pos = str3.find("World");
if (pos != string::npos) {
cout << "Found 'World' at position: " << pos << endl; // 输出: Found 'World' at position: 7
}
// 替换子字符串
string str4 = str3.replace(0, 6, "Hi");
cout << "str4 after replace: " << str4 << endl; // 输出: str4 after replace: Hi, World!
// 插入子字符串
str4.insert(3, " there");
cout << "str4 after insert: " << str4 << endl; // 输出: str4 after insert: Hi there, World!
// 删除子字符串
str4.erase(2, 6);
cout << "str4 after erase: " << str4 << endl; // 输出: str4 after erase: Hi, World!
// 转换为大写
for (char &c : str4) {
c = toupper(c);
}
cout << "str4 in uppercase: " << str4 << endl; // 输出: str4 in uppercase: HI, WORLD!
return 0;
}
std::string 类创建字符串对象。+ 操作符将两个字符串连接在一起。length() 方法获取字符串的长度。find() 方法查找子字符串的位置,如果找不到返回 string::npos。replace() 方法替换指定位置的子字符串。insert() 方法在指定位置插入子字符串。erase() 方法删除指定位置的子字符串。上一篇:c++ 泛型
下一篇:c++ 重载运算符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站