c++ string 库函数
时间: 2023-10-22 14:04:42 浏览: 187
C++ string 库函数包括以下常用函数:
1. `size()`:返回字符串的长度。
2. `empty()`:判断字符串是否为空。
3. `clear()`:清空字符串。
4. `substr(pos, len)`:返回从 pos 开始长度为 len 的子串。
5. `append(str)`:在字符串末尾添加 str。
6. `replace(pos, len, str)`:用 str 替换从 pos 开始长度为 len 的子串。
7. `find(str, pos)`:从 pos 开始查找 str 第一次出现的位置,返回位置下标,如果没找到则返回 string::npos。
相关问题
c++ string 库函数 排序
C++ string库函数中没有排序函数,但可以使用STL中的sort函数对字符串进行排序。sort函数可以对字符串中的字符进行升序或降序排序。
例如,对一个字符串进行升序排序可以使用以下代码:
```cpp
#include <algorithm>
#include <string>
using namespace std;
int main() {
string s = "hello world";
sort(s.begin(), s.end());
cout << s << endl; // 输出 dehllloorw
return 0;
}
```
c++string 库函数的用法
### C++ `string` 库函数使用教程
#### 查找子串或字符的位置
在处理字符串时,经常需要查找某个子串或特定字符首次出现的位置。可以使用 `find` 函数来完成这一操作。
- **基本形式**: `size_t find (const string& str, size_t pos = 0) const noexcept;`
- 如果找到目标,则返回其位置;如果没有找到,则返回 `std::string::npos`[^3]。
```cpp
#include <iostream>
#include <string>
int main() {
std::string s = "Hello world";
// 寻找单个字符 'o'
auto index_char = s.find('o');
if(index_char != std::string::npos){
std::cout << "'o' found at position: " << index_char << '\n';
}
// 寻找子串 "world"
auto index_str = s.find("world");
if(index_str != std::string::npos){
std::cout << "\"world\" found starting from position: " << index_str << '\n';
}
}
```
#### 字符串比较
当两个字符串之间存在大小关系判断需求时,可利用标准库提供的 `strcmp` 或者直接通过运算符来进行对比。对于更复杂的场景,建议采用成员函数 `compare()` 方法实现更为灵活多样的匹配逻辑[^1]。
```cpp
// 使用 compare 成员函数进行比较
if(s.compare(t) == 0){
// 表明两字符串相等...
}
// 或者简单地用关系运算符
if(s == t){
// 同样表示两者相同...
}
```
需要注意的是,在现代编程实践中推荐优先考虑基于对象的操作方式而非传统的C风格API调用,因为前者通常具有更好的安全性以及易读性特点。
阅读全文
相关推荐













