#include <iostream>
#include <string>
int main() {
// 创建一个字符串对象
std::string greeting = "Hello, World!";
// 输出字符串内容
std::cout << greeting << std::endl;
// 获取字符串长度
std::cout << "Length of string: " << greeting.length() << std::endl;
// 访问字符串中的单个字符
std::cout << "First character: " << greeting[0] << std::endl;
// 字符串拼接
std::string name = "C++";
std::string welcomeMessage = greeting + " Welcome to " + name;
std::cout << welcomeMessage << std::endl;
// 查找子字符串
size_t pos = welcomeMessage.find("Welcome");
if (pos != std::string::npos) {
std::cout << "Found 'Welcome' at position: " << pos << std::endl;
} else {
std::cout << "'Welcome' not found" << std::endl;
}
// 替换子字符串
std::string replaced = welcomeMessage.replace(pos, 7, "Greetings");
std::cout << "After replacement: " << replaced << std::endl;
return 0;
}
std::string
类型创建字符串对象,例如 std::string greeting = "Hello, World!";
。std::cout
输出字符串的内容。length()
方法获取字符串的长度。greeting[0]
。+
操作符将多个字符串连接在一起。find()
方法查找子字符串的位置。如果找到返回位置索引,否则返回 std::string::npos
。replace()
方法替换指定位置的子字符串。这段代码展示了 C++ 中常用的字符串操作方法。
上一篇:c++入门
下一篇:c++指针
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站