c++字符串操作常用函数

C++中的标准库<string>提供了一系列用于操作字符串的常用函数。下面列举了一些常见的字符串操作函数:

  1. length() 或 size(): 返回字符串的长度。
  2. empty(): 判断字符串是否为空。
  3. clear(): 清空字符串内容。
  4. substr(pos, len): 返回从指定位置开始的指定长度子串。
  5. append(str): 在字符串末尾追加指定字符串。
  6. insert(pos, str): 在指定位置插入字符串。
  7. erase(pos, len): 删除从指定位置开始的指定长度字符。
  8. replace(pos, len, str): 用指定字符串替换从指定位置开始的指定长度字符。
  9. find(str): 查找指定字符串在当前字符串中的第一个出现位置。
  10. rfind(str): 查找指定字符串在当前字符串中的最后一个出现位置。
  11. substr(pos, len): 返回从指定位置开始的指定长度子串。
  12. compare(str,pos,len): 比较字符串与指定字符串的大小关系。
    #include <iostream>
    #include <string>
    
    int main() {
        std::string str = "Hello, World!";
        
        std::cout << "字符串长度: " << str.length() << std::endl;
        std::cout << "字符串是否为空: " << (str.empty() ? "是" : "否") << std::endl;
    
        str.clear();
        std::cout << "清空后的字符串: " << str << std::endl;
    
        str = "Hello, World!";
        std::string sub = str.substr(7, 5);
        std::cout << "子串: " << sub << std::endl;
    
        str.append(" How are you?");
        std::cout << "追加后的字符串: " << str << std::endl;
    
        str.insert(12, " my friend");
        std::cout << "插入后的字符串: " << str << std::endl;
    
        str.erase(0, 6);
        std::cout << "删除后的字符串: " << str << std::endl;
    
        str.replace(7, 5, "World");
        std::cout << "替换后的字符串: " << str << std::endl;
    
        int pos = str.find("World");
        std::cout << "查找位置: " << pos << std::endl;
    
        return 0;
    }
    
    #include <iostream>
    #include <string>
    
    int main() {
        std::string str1 = "Hello";
        std::string str2 = "Hellp";
        int n = 4;
    
        int result = str1.compare(0, n, str2, 0, n);
    
        if (result == 0) {
            std::cout << "前" << n << "项相等" << std::endl;
        } else if (result < 0) {
            std::cout << "str1排在str2前面" << std::endl;
        } else {
            std::cout << "str1排在str2后面" << std::endl;
        }
    
        return 0;
    }
    

  • 14
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值