#include <iostream>
#include <string>
int main() {
// 创建一个字符串对象
std::string str = "Hello, World!";
// 输出字符串内容
std::cout << str << std::endl;
// 获取字符串长度
std::cout << "Length: " << str.length() << std::endl;
// 访问字符串中的单个字符
std::cout << "First character: " << str[0] << std::endl;
// 字符串拼接
std::string part1 = "Hello";
std::string part2 = "World";
std::string greeting = part1 + ", " + part2 + "!";
std::cout << "Greeting: " << greeting << std::endl;
// 查找子字符串的位置
size_t pos = str.find("World");
if (pos != std::string::npos) {
std::cout << "Found 'World' at position: " << pos << std::endl;
} else {
std::cout << "'World' not found" << std::endl;
}
// 替换子字符串
str.replace(str.find("World"), 5, "C++");
std::cout << "After replacement: " << str << std::endl;
return 0;
}
#include <string> 是用于处理 C++ 中的字符串操作。std::string str = "Hello, World!"; 创建了一个名为 str 的字符串对象,并初始化为 "Hello, World!"。std::cout 输出字符串的内容。str.length() 返回字符串的长度。str[0] 返回第一个字符。+ 操作符可以将多个字符串拼接在一起。str.find("World") 查找子字符串 "World" 在字符串中的位置。如果找到返回位置,否则返回 std::string::npos。str.replace() 方法用于替换字符串中的一部分内容。希望这段代码和解释对你有帮助!
上一篇:c++多态
下一篇:c++在线编译
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站