#include <iostream>
#include <string>
using namespace std;
int main() {
// 创建字符串
string str1 = "Hello";
string str2 = "World";
// 连接两个字符串
string str3 = str1 + " " + str2;
cout << "连接后的字符串: " << str3 << endl;
// 获取字符串长度
int length = str3.length();
cout << "字符串长度: " << length << endl;
// 查找子字符串的位置
size_t position = str3.find("World");
if (position != string::npos) {
cout << "子字符串 'World' 的位置: " << position << endl;
} else {
cout << "未找到子字符串 'World'" << endl;
}
// 替换子字符串
string replacedStr = str3.replace(6, 5, "C++");
cout << "替换后的字符串: " << replacedStr << endl;
// 字符串转为大写
for (char &c : replacedStr) {
c = toupper(c);
}
cout << "转换为大写的字符串: " << replacedStr << endl;
return 0;
}
std::string 类型创建字符串对象。+ 操作符将两个字符串连接起来。length() 方法获取字符串的长度。find() 方法查找子字符串的位置,如果找不到返回 string::npos。replace() 方法替换指定位置的子字符串。toupper() 函数将其转换为大写。希望这些示例代码和解释对你有帮助!
上一篇:c++ 转义字符
下一篇:c++调用函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站