#include <iostream>
#include <string>
int main() {
// 创建一个空字符串
std::string emptyString;
std::cout << "Empty string: '" << emptyString << "'" << std::endl;
// 创建并初始化字符串
std::string helloString = "Hello, World!";
std::cout << "Initialized string: " << helloString << std::endl;
// 字符串连接
std::string part1 = "Hello";
std::string part2 = "World";
std::string greeting = part1 + ", " + part2 + "!";
std::cout << "Concatenated string: " << greeting << std::endl;
// 字符串长度
std::cout << "Length of greeting string: " << greeting.length() << std::endl;
// 访问字符串中的字符
std::cout << "First character of greeting: " << greeting[0] << std::endl;
// 子字符串
std::string subString = greeting.substr(0, 5);
std::cout << "Substring from greeting: " << subString << std::endl;
// 查找子字符串
size_t found = greeting.find("World");
if (found != std::string::npos) {
std::cout << "Found 'World' at position: " << found << std::endl;
} else {
std::cout << "'World' not found" << std::endl;
}
return 0;
}
std::string emptyString; 创建一个空的字符串对象。std::string helloString = "Hello, World!"; 使用字面量初始化字符串。+ 操作符将多个字符串连接在一起。length() 方法获取字符串的长度。[] 访问字符串中的单个字符。substr(start, length) 方法提取子字符串。find(substring) 方法查找子字符串的位置,如果未找到则返回 std::string::npos。这段代码展示了 C++ 中 std::string 类的基本用法和常见操作。
上一篇:c++ ceil函数
下一篇:c++ exit
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站