C++学习,String类成员函数

基本语法

std::string 类的基本语法如下:

  • 声明字符串变量:

    std::string str;
  • 初始化字符串:

    std::string str = "Hello";
  • 使用 + 连接字符串:

    std::string str1 = "Hello, ";
    std::string str2 = "World!";
    std::string result = str1 + str2;

 

std::string 成员函数:

函数名描述示例代码
size()返回字符串的长度。std::cout << str.size();
length()返回字符串的长度。std::cout << str.length();
empty()判断字符串是否为空。std::cout << (str.empty() ? "Y" : "N");
operator[]访问字符串中指定位置的字符。std::cout << str[0];
at()访问字符串中指定位置的字符(带边界检查)。std::cout << str.at(0);
substr()返回指定位置开始的子字符串。std::string sub = str.substr(0, 8);
find()查找子字符串在字符串中的位置。std::cout << str.find("sub1") << std::endl;
rfind()从字符串末尾开始查找子字符串的位置。std::cout << str.rfind("sub1") << std::endl;
replace()替换字符串中的部分内容。str.replace(pos, length, "new_substring");
append()在字符串末尾添加内容。str.append(" more");
insert()在指定位置插入内容。str.insert(pos, "inserted");
erase()删除指定位置的字符或子字符串。str.erase(pos, length);
clear()清空字符串。str.clear();
c_str()返回 C 风格的字符串(以 null 结尾)。const char* cstr = str.c_str();
data()返回指向字符数据的指针(C++11 及之后的版本)。const char* data = str.data();
compare()比较两个字符串内容。int result = str.compare("hello");
find_first_of()查找第一个匹配任意字符的位置。size_t pos = str.find_first_of("hello");
find_last_of()查找最后一个匹配任意字符的位置。size_t pos = str.find_last_of("hello");
find_first_not_of()查找第一个不匹配任意字符的位置。size_t pos = str.find_first_not_of("hello");
find_last_not_of()查找最后一个不匹配任意字符的位置。size_t pos = str.find_last_not_of("hello");

 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值