#include <iostream>
#include <string>
using namespace std;
int main() {
// 创建字符串对象
string str1 = "Hello, World!";
// 1. size() - 获取字符串长度
cout << "Size of str1: " << str1.size() << endl; // 输出: 13
// 2. empty() - 检查字符串是否为空
string str2 = "";
if (str2.empty()) {
cout << "str2 is empty" << endl; // 输出: str2 is empty
}
// 3. append() - 追加字符串
str1.append(" Welcome!");
cout << "After appending: " << str1 << endl; // 输出: Hello, World! Welcome!
// 4. substr() - 获取子字符串
string subStr = str1.substr(0, 5);
cout << "Substring from index 0 to 4: " << subStr << endl; // 输出: Hello
// 5. find() - 查找子字符串的位置
size_t pos = str1.find("World");
if (pos != string::npos) {
cout << "Position of 'World': " << pos << endl; // 输出: Position of 'World': 7
}
// 6. replace() - 替换子字符串
str1.replace(7, 5, "Universe");
cout << "After replacing 'World' with 'Universe': " << str1 << endl; // 输出: Hello, Universe! Welcome!
// 7. erase() - 删除子字符串
str1.erase(14, 8); // 删除从索引14开始的8个字符
cout << "After erasing: " << str1 << endl; // 输出: Hello, Universe!
// 8. compare() - 比较两个字符串
string str3 = "Hello, Universe!";
if (str1.compare(str3) == 0) {
cout << "str1 and str3 are equal" << endl;
} else {
cout << "str1 and str3 are not equal" << endl; // 输出: str1 and str3 are equal
}
return 0;
}
string::npos
。希望这些示例和解释对你有帮助!
上一篇:c++小游戏编程代码
下一篇:c++语言程序设计
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站