#include <iostream>
#include <string>
int main() {
// 创建一个空的字符串
std::string emptyString;
std::cout << "Empty string: '" << emptyString << "'" << std::endl;
// 使用构造函数创建字符串
std::string hello("Hello, World!");
std::cout << "Hello string: " << hello << std::endl;
// 使用+运算符连接字符串
std::string greeting = "Hello" + ", " + "World!";
std::cout << "Greeting string: " << greeting << std::endl;
// 使用append方法连接字符串
std::string welcome = "Welcome";
welcome.append(" to C++");
std::cout << "Welcome string: " << welcome << std::endl;
// 访问字符串中的字符
std::cout << "First character of hello: " << hello[0] << std::endl;
// 获取字符串长度
std::cout << "Length of hello: " << hello.length() << std::endl;
// 查找子字符串的位置
size_t position = hello.find("World");
if (position != std::string::npos) {
std::cout << "Position of 'World': " << position << std::endl;
} else {
std::cout << "'World' not found." << std::endl;
}
// 替换子字符串
hello.replace(7, 5, "C++");
std::cout << "After replacing: " << hello << std::endl;
return 0;
}
创建字符串:
std::string emptyString;
:创建一个空字符串。std::string hello("Hello, World!");
:使用构造函数创建一个包含初始值的字符串。字符串连接:
+
运算符可以将多个字符串连接在一起。append
方法也可以用于连接字符串,但它是通过调用对象的方法来实现的。访问字符串中的字符:
hello[0]
)来访问字符串中的单个字符。获取字符串长度:
length()
方法返回字符串的长度。查找子字符串:
find
方法用于查找子字符串的位置,如果找不到则返回std::string::npos
。替换子字符串:
replace
方法用于替换指定位置和长度的子字符串。上一篇:visual c++怎么运行程序
下一篇:c++换行指令
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站