cpp string
时间: 2023-07-21 12:07:51 浏览: 44
好的,您想了解关于 C++ 中的字符串(string)吗?
在 C++ 中,字符串类型被定义为 std::string,这是一个标准库类。使用字符串时,需要包含头文件 <string>。
可以使用赋值运算符和构造函数来创建字符串对象。例如:
```cpp
// 使用赋值运算符创建字符串对象
std::string str1 = "Hello, world!";
// 使用构造函数创建字符串对象
std::string str2("I love C++ programming!");
```
字符串对象提供了许多常用的方法,例如:
- size():返回字符串的长度
- empty():判断字符串是否为空
- clear():清空字符串
- append():在字符串末尾添加字符或字符串
- substr():截取子字符串
- find():查找指定子串的位置
例如,可以使用以下代码演示一些常用的字符串操作:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello, world!";
std::string str2("I love C++ programming!");
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
std::cout << "str1 length: " << str1.size() << std::endl;
std::cout << "str2 length: " << str2.size() << std::endl;
std::cout << "str1 is empty: " << (str1.empty() ? "true" : "false") << std::endl;
std::cout << "str2 is empty: " << (str2.empty() ? "true" : "false") << std::endl;
str1.clear();
std::cout << "str1 after clear: " << str1 << std::endl;
str2.append(" And I enjoy it!");
std::cout << "str2 after append: " << str2 << std::endl;
std::string sub = str2.substr(7, 3);
std::cout << "sub string of str2: " << sub << std::endl;
int pos = str2.find("C++");
if (pos != std::string::npos) {
std::cout << "C++ is found in str2 at position " << pos << std::endl;
} else {
std::cout << "C++ is not found in str2" << std::endl;
}
return 0;
}
```
希望这能回答您的问题!