doc/notebook/docs/C++/3.string.md

77 lines
2.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

1. `std::string`: C++中的字符串类,提供了丰富的成员函数用于字符串操作。常用的成员函数包括:
- `size()`: 返回字符串的长度。
- `length()`: 返回字符串的长度。
- `empty()`: 判断字符串是否为空。
- `clear()`: 清空字符串内容。
- `substr(pos, len)`: 返回从位置`pos`开始长度为`len`的子字符串。
- `find(str, pos)`: 在字符串中查找子字符串`str`,并返回第一次出现的位置。
- `replace(pos, len, str)`: 替换字符串中从位置`pos`开始长度为`len`的子串为字符串`str`。
- `append(str)`: 在字符串末尾追加字符串`str`。
- `insert(pos, str)`: 在指定位置插入字符串`str`。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
// 使用成员函数进行字符串操作
std::cout << "Length: " << str.length() << std::endl;
std::cout << "Substring: " << str.substr(0, 5) << std::endl;
str.replace(7, 5, "C++");
std::cout << "Replaced: " << str << std::endl;
str.append(" Goodbye!");
std::cout << "Appended: " << str << std::endl;
str.insert(0, "Greetings, ");
std::cout << "Inserted: " << str << std::endl;
return 0;
}
```
2. `std::getline()`: 从输入流中读取一行数据并存储到字符串中
```cpp
#include <iostream>
#include <string>
int main() {
std::string line;
std::cout << "Enter a line of text: ";
std::getline(std::cin, line);
std::cout << "You entered: " << line << std::endl;
return 0;
}
```
3. 字符串查找和比较函数
- `std::string::find(str, pos)`: 在字符串中查找子字符串`str`并返回第一次出现的位置
- `std::string::rfind(str, pos)`: 在字符串中从后向前查找子字符串`str`并返回第一次出现的位置
- `std::string::find_first_of(str, pos)`: 在字符串中查找任意字符集合`str`中的字符返回第一次出现的位置
- `std::string::find_last_of(str, pos)`: 在字符串中从后向前查找任意字符集合`str`中的字符返回第一次出现的位置
- `std::string::compare(str)`: 比较字符串与`str`返回大小关系0表示相等负数表示小于正数表示大于)。
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
if (str.find("world") != std::string::npos) {
std::cout << "Substring found!" << std::endl;
}
if (str.compare("Hello, C++!") == 0) {
std::cout << "Strings are equal." << std::endl;
}
return 0;
}
```