string

  • 🔍 查找相关

    // 查找子串
    size_t pos = str.find("sub");      // 查找首次出现
    size_t pos = str.rfind("sub");     // 从后往前查找
    size_t pos = str.find_first_of("aeiou");    // 查找任意字符首次出现
    size_t pos = str.find_last_of("aeiou");     // 查找任意字符最后出现
    
    // C++23 新增
    bool contains = str.contains("sub");  // 检查是否包含子串
    
  • 📏 长度和容量

    str.length();     // 字符串长度
    str.size();       // 同 length()
    str.empty();      // 检查是否为空
    
  • ✂️ 子串操作

    // 获取子串
    string sub = str.substr(pos, count);  // 从pos开始取count个字符
    //若超出了则到结尾即终止,因此count的大小不是很重要
    string sub = str.substr(pos);         // 从pos到结尾
    
    // 删除
    str.erase(pos, count);    // 删除从pos开始的count个字符
    str.erase(iterator);      // 删除迭代器位置
    str.erase(start_it, end_it); // 删除迭代器范围
    
    /*e.g
    string s6 = str;
    s6.erase(s6.begin() + 7, s6.begin() + 13);  // 删除"World!"
    cout << "6. erase(iter1, iter2): " << s6 << std::endl;
    // 结果: "Hello,  Programming is fun!"
    */
    
    str.clear();              // 清空字符串
    
    // 插入(此处的插入都是插在前面)
    str.insert(pos, "text");  // 在pos处插入
    str.insert(pos, count, 'c'); // 插入count个字符c
    //这里如果count超出了str的结尾则到结尾就终止
    
posted @ 2025-12-05 16:38  channy_zheng  阅读(7)  评论(0)    收藏  举报