#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 str2 = " C++";
str += str2;
std::cout << "Concatenated string: " << str << std::endl;
// 查找子字符串
size_t pos = str.find("C++");
if (pos != std::string::npos) {
std::cout << "Found 'C++' at position: " << pos << std::endl;
} else {
std::cout << "'C++' not found" << std::endl;
}
// 替换子字符串
str.replace(str.find("World"), 5, "Universe");
std::cout << "Replaced string: " << str << std::endl;
return 0;
}
std::string
类来创建字符串对象。std::cout
输出字符串内容。length()
方法获取字符串的长度。[]
访问字符串中的单个字符。+=
操作符连接两个字符串。find()
方法查找子字符串的位置,如果找不到返回 std::string::npos
。replace()
方法替换指定位置的子字符串。希望这些示例能帮助你更好地理解如何在 C++ 中使用 std::string
。
上一篇:c++helloworld代码
下一篇:c++恶搞代码
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站