#include <iostream>
#include <string> // 引入C++标准库中的string类
int main() {
// 创建一个字符串对象
std::string greeting = "Hello, World!";
// 输出字符串内容
std::cout << greeting << std::endl;
// 使用string类的成员函数
std::string name = "Alice";
std::string message = "Welcome ";
message += name; // 拼接字符串
message.append(" to the C++ world!"); // 使用append方法拼接字符串
// 输出拼接后的字符串
std::cout << message << std::endl;
// 使用find方法查找子串的位置
size_t pos = message.find("C++");
if (pos != std::string::npos) {
std::cout << "Found 'C++' at position: " << pos << std::endl;
} else {
std::cout << "'C++' not found" << std::endl;
}
return 0;
}
#include <string>
引入了C++标准库中的string
类,使得我们可以使用std::string
类型。std::string greeting = "Hello, World!";
创建了一个名为greeting
的字符串对象,并初始化为"Hello, World!"。std::cout
将字符串内容输出到控制台。+=
操作符和append
方法来拼接字符串。find
方法查找子串在字符串中的位置。如果找到,返回其起始位置;否则返回std::string::npos
。这个示例展示了如何使用C++中的string
类进行基本的字符串操作。
上一篇:c++中const的用法
下一篇:c++ typeof
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站