#include <iostream>
#include <string>
int main() {
// 创建一个字符串对象
std::string str = "Hello, C++";
// 输出字符串内容
std::cout << str << std::endl;
// 获取字符串长度
std::cout << "字符串长度: " << str.length() << std::endl;
// 访问字符串中的单个字符
std::cout << "第一个字符: " << str[0] << std::endl;
// 字符串拼接
std::string part1 = "Hello";
std::string part2 = " World";
std::string greeting = part1 + part2;
std::cout << "拼接后的字符串: " << greeting << std::endl;
// 查找子字符串
std::size_t found = str.find("C++");
if (found != std::string::npos) {
std::cout << "找到 'C++',位置在: " << found << std::endl;
} else {
std::cout << "未找到 'C++'" << std::endl;
}
// 替换子字符串
std::string newStr = str.replace(7, 3, "World");
std::cout << "替换后的字符串: " << newStr << std::endl;
return 0;
}
std::string 类来创建字符串对象。std::cout 输出字符串的内容。length() 方法获取字符串的长度。+ 运算符将两个字符串拼接在一起。find() 方法查找子字符串的位置。replace() 方法替换指定位置的子字符串。上一篇:c++排序
下一篇:c++数字转字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站