#include <iostream>
#include <string>
int main() {
// 创建一个字符串对象
std::string greeting = "Hello, C++!";
// 输出字符串
std::cout << greeting << std::endl;
// 获取字符串长度
std::cout << "Length of the string: " << greeting.length() << std::endl;
// 访问字符串中的单个字符
std::cout << "First character: " << greeting[0] << std::endl;
// 连接两个字符串
std::string part1 = "Hello";
std::string part2 = "World";
std::string combined = part1 + ", " + part2 + "!";
std::cout << "Combined string: " << combined << std::endl;
// 查找子字符串的位置
std::string sentence = "This is a sample sentence.";
size_t position = sentence.find("sample");
if (position != std::string::npos) {
std::cout << "Found 'sample' at position: " << position << std::endl;
} else {
std::cout << "'sample' not found." << std::endl;
}
// 替换子字符串
std::string text = "C++ is fun.";
text.replace(0, 3, "Programming");
std::cout << "Replaced string: " << text << std::endl;
return 0;
}
std::string 类来创建字符串对象。std::cout 输出字符串内容。length() 方法获取字符串的长度。+ 操作符连接两个字符串。find() 方法查找子字符串的位置,如果找不到返回 std::string::npos。replace() 方法替换指定位置的子字符串。以上代码展示了如何在 C++ 中使用 std::string 类进行基本的字符串操作。
上一篇:c++ 单例
下一篇:c++ 字典
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站