当前位置: 首页 > news >正文

c++中字符串string常用的函数

在C++中, std::string 类有许多常用函数,以下是一些常见的:

1. length() 或 size() :返回字符串的长度(字符个数),二者功能相同。例如:
#include <iostream>
#include <string>
int main() {
    std::string str = "hello";
    std::cout << str.length() << std::endl; 
    std::cout << str.size() << std::endl; 
    return 0;
}
2. empty() :检查字符串是否为空,为空返回 true ,否则返回 false 。
#include <iostream>
#include <string>
int main() {
    std::string str1 = "";
    std::string str2 = "world";
    std::cout << std::boolalpha << str1.empty() << std::endl; 
    std::cout << std::boolalpha << str2.empty() << std::endl; 
    return 0;
}
 
3. append() :在字符串末尾追加另一个字符串或字符序列。
#include <iostream>
#include <string>
int main() {
    std::string str = "hello";
    str.append(" world");
    std::cout << str << std::endl; 
    return 0;
}
pop_back():删除字符串最后一个字符
str。pop_back():
4. substr() :返回字符串的子串。接受起始位置和长度作为参数。
cpp
  
#include <iostream>
#include <string>
int main() {
    std::string str = "hello world";
    std::string sub = str.substr(0, 5);
    std::cout << sub << std::endl; 
    return 0;
}
5. find() :在字符串中查找指定子串或字符的位置,返回首次出现的位置索引,若未找到返回 std::string::npos 。
cpp
#include <iostream>
#include <string>
int main() {
    std::string str = "hello world";
    size_t pos = str.find("world");
    if (pos != std::string::npos) {
        std::cout << "子串位置: " << pos << std::endl; 
    }
    return 0;
}
6. replace() :用新的子串替换字符串中指定的子串。
#include <iostream>
#include <string>
int main() {
    std::string str = "hello world";
    str.replace(6, 5, "C++");
    std::cout << str << std::endl; 
    return 0;
}
7. c_str() :返回一个指向以空字符结尾的C风格字符串的指针。常用于与C语言函数接口。
#include <iostream>
#include <string>
#include <cstdio>
int main() {
    std::string str = "hello";
    const char* cstr = str.c_str();
    printf("%s\n", cstr); 
    return 0;
}

相关文章:

  • AMBA-CHI协议详解(二十二)
  • Next-Slides 更新记录
  • AcWing 5960:输出前k大的数 ← 小根堆
  • centos 磁盘重新分割,将原来/home 下部分空间转移到 / 根目录下
  • Idea集成docker通过ca加密实现镜像打包
  • freetros 信号量使用方法实例解析
  • 【 <二> 丹方改良:Spring 时代的 JavaWeb】之 Spring Boot 的自动配置:约定优于配置的设计美学
  • 激光雷达点云改善汇总
  • FastGPT原理分析-数据集创建第一步
  • Java学习第十二天--集合
  • Fisher信息、梯度方差与学习率调度器的计算流程
  • 3.17[Q]CV Bézier curve
  • TCP简单链接的编程实现
  • 使用vue3+el-form实现动态新增名称,值,并对名称进行必填校验
  • 电脑如何录屏
  • 华为OD机试 - 仿LISP运算 - 逻辑分析(Java 2023 B卷 200分)
  • C语言之 循环语句:程序运行的核心动力(上)
  • 一键批量txt转DWG,DWG转txt——插件实现 CAD c#二次开发
  • 消失的密文
  • 消息队列,阻塞队列的实现
  • 商务部新闻发言人就出口管制管控名单答记者问
  • 俄官员说将适时宣布与乌克兰谈判代表
  • 广东省中医院脾胃病科大科主任张北平病逝,年仅52岁
  • 张笑宇:物质极大丰富之后,我们该怎么办?
  • 女高音吴睿睿“古词新唱”,穿着汉服唱唐诗宋词
  • 巫蛊:文化的历史暗流