c++字符串的操作技巧(更新ing)

查询

除了find()之外还有: 

find()方法:

用于在字符串中查找子字符串或字符的位置。它返回子字符串首次出现的起始索引(从0开始),如果未找到则返回std::string::npos(一个特殊常量,通常是-1或size_t的最大值)。

size_t find(const string& str, size_t pos = 0) const;  // 查找子字符串
size_t find(const char* s, size_t pos = 0) const;      // 查找C风格字符串
size_t find(char c, size_t pos = 0) const;             // 查找单个字符

条件判断: 

size_t found = s.find(target);
if (found != string::npos)

  1. 大小写敏感find()区分大小写。如需不区分大小写,需自行转换字符串(如全转小写)。

  2. 性能find()的时间复杂度为O(n*m),其中n和m分别是主串和子串长度。

最值

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {3, 1, 4, 1, 5, 9, 2};

    // 使用 min_element 获取最小值的迭代器
    auto min_it = min_element(v.begin(), v.end());//这里返回值是地址

    // 计算最小值的下标(从 0 开始)
    int min_index = distance(v.begin(), min_it);

    cout << "最小值: " << *min_it << endl;     // 输出: 1
    cout << "位置: " << min_index << endl;      // 输出: 1(第 2 个元素)

    return 0;
}

删除操作 

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main() {
    // 删除特定字符
    string s = "hello world";
    s.erase(remove(s.begin(), s.end(), 'l'), s.end());
    cout << s << endl;  // 输出: "heo word"
    
    // 删除特定子串
    s = "hello world";
    size_t pos;
    while ((pos = s.find("ll")) != string::npos) {
        s.erase(pos, 2);
    }
    cout << s << endl;  // 输出: "heo world"
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值