• 【探索C++】string类详解



            在C++中,字符串处理是非常重要的一部分,而stringSTL中封装的一个重要工具,用于处理字符串。它的强大功能在上上篇博客中有些许讲解,那么本文将介绍C++中字符串的基本概念以及string类的构造方法,让你彻底理解和掌握C++中的string类

    一. C++中字符串的概念

            在C++中,字符串是文本数据的重要形式,用于存储和处理文本信息。C++中,有多种方式来表示字符串,其中最常用的是使用string。掌握好string类对新手是及其重要的。

    1.1 string

       string是C++标准模板库(STL)中封装的一个类,用于表示和操作字符串。它是对字符数组(char数组)或字符指针(char *)的封装,提供了一系列的成员函数(后文马上也会介绍到详细的常见成员用法等),简化了字符串的操作。

    1.2 string类的优势

            与传统的字符数组或字符指针相比,string有以下优势:

    • 内存管理string自动管理字符串的内存,不需要手动释放内存或担心内存越界问题。

    • 操作简便string提供了丰富的成员函数,使得字符串的操作变得更加简单和灵活。

    • 安全性:由于内存管理由string自动处理,可以减少许多常见的内存错误

    1.3 输入字符串

            需要注意的是,如果使用 cin 来输入字符串,它会在遇到空格时停止输入。如果需要获取包含空格的输入,应使用getline函数,如下所示:

    1. string name;
    2. getline(cin, name); // 通过getline获取包含空格的输入

            getline函数的具体用法呢上一篇博客中也有详细介绍,感兴趣请翻阅查看。

    二. string字符串的构造

            现在让我们来看一下如何构造string字符串

    2.1 默认无参构造函数

       string具有默认无参构造函数,可以用来创建一个空的字符串对象,如下所示:

    string str; // 创建一个空的字符串对象
    

    2.2 有参构造函数

       string也提供了有参构造函数,用于根据给定的内容创建字符串对象。以下是一些示例:

    • 使用字符串字面值创建字符串对象:
    1. string str1("hello world"); // 使用字符串字面值创建字符串对象
    2. string str2 = "hello world"; // 另一种方式
    • 使用字符和重复次数创建字符串对象:
    string str3(10, 'A'); // 创建包含10'A'字符的字符串
    

    2.3 拷贝构造函数

        string还具有拷贝构造函数,可以通过复制已有的字符串对象来创建新的字符串对象,如下所示:

    1. string str4 = str1; // 使用拷贝构造函数创建新的字符串对象
    2. string str5(str2); // 另一种使用拷贝构造函数的方式

    三. 重载运算符

            学习C语言时大家肯定对重载没有太多印象,如果你能记起 & 是被重载的那么你的C语言是扎实的,它既可以是按位与操作符又是取地址操作符;那么在C++中,string重载了许多操作符使得字符串的操作更加方便和灵活。下面我们将介绍一些常见的操作符重载函数。

    3.1 赋值运算符(=)

            赋值运算符(=)被重载用于将一个字符串赋值给另一个字符串。例如:

    1. string str1 = "hello world"; // 使用赋值运算符将一个字符串赋值给str1
    2. string str2;
    3. str6 = str1; // 使用赋值运算符将str4的值赋给str2
    4. cout << "str2 = " << str2 << endl;

    3.2 左移运算符(<<)

            左移运算符(<<)被重载用于将字符串输出到输出流,通常用于输出到控制台。例如:

    1. string str1 = "hello world";
    2. cout << "str1 = " << str1 << endl; // 使用左移运算符将str1输出到控制台

    3.3 右移运算符(>>)

            右移运算符(>>)被重载用于从输入流中读取字符串。例如:

    1. string str1;
    2. cin >> str1; // 使用右移运算符从输入流中读取字符串

    3.4 数组下标操作符([])

            数组下标操作符([])被重载,使得可以通过下标访问字符串中的字符。例如:

    1. string str1 = "hello world";
    2. char c = str1[2]; // 使用数组下标操作符访问字符串的第三个字符(下标从0开始)
    3. cout << "c = " << c << endl; // 输出 c = l

    3.5 加法运算符(+)

            加法运算符(+)被重载用于将两个字符串连接起来。例如:

    1. string str1 = "hello ";
    2. string str2 = "world";
    3. string str3;
    4. str3 = str1 + str2; // 使用加法运算符连接两个字符串

    3.6 加法赋值运算符(+=)

            加法赋值运算符(+=)被重载用于将一个字符串与另一个字符串连接并将结果赋值给原字符串。例如:

    1. string str1 = "hello ";
    2. string str2 = "world";
    3. str1 += str2; // 使用加法赋值运算符连接并赋值

    3.7 关系运算符(==、!=、<、>、<=、>=)

            关系运算符(==!=<><=>=)被重载,用于比较两个字符串的大小关系。例如:

    1. string str1 = "apple";
    2. string str2 = "banana";
    3. if (str1 < str2) {
    4. cout << "str1 小于 str2" << endl;
    5. } else {
    6. cout << "str1 大于等于 str2" << endl;
    7. }

    注意:

            只要你的类(stig字符串)里面,只要对运算符有做重载,你都可以直接去用这个运算符,如果没有,则会报以下这个错误:
     

    no match for‘operator|’         //operator是关键,表示后面的这个运算符没有做重载

    四、C++的string成员函数

            之前的一篇博客已经详细的讲解了string类强大的功能,那么今天我们来看看该类下到底有多少常用的成员函数,用于操作和处理字符串。

    4.1 length()size()

            返回字符串的长度,即字符的个数。

    1. string str = "hello";
    2. int len = str.length();
    3. // 或 int len = str.size();

    4.2 empty()

            检查字符串是否为空,返回true表示为空,false表示非空。

    1. string str = "hello";
    2. bool isEmpty = str.empty(); // 返回 false

    4.3 clear()

            清空字符串的内容,使其成为空字符串。

    1. string str = "hello";
    2. str.clear(); // str现在是一个空字符串

    4.4 substr(start, length)

            返回从指定位置开始的指定长度的子字符串。

    1. string str = "hello world";
    2. string sub = str.substr(6, 5); // sub = "world"

    4.5 find(substring)

            在字符串中查找子字符串,并返回第一次出现的位置(索引),如果未找到则返回string::npos

    1. string str = "hello world";
    2. size_t pos = str.find("world"); // pos = 6

    4.6 replace(start, length, new_str)

            用新字符串替换指定位置的子字符串。

    1. string str = "hello world";
    2. str.replace(6, 5, "there"); // str = "hello there"

    4.7 append(new_str)+=

            将新字符串追加到原字符串的末尾。

    1. string str = "hello";
    2. str.append(" world"); // str = "hello world"
    3. // 或者
    4. string str1 = "hello";
    5. string str2 = " world";
    6. str1 += str2; // str1 = "hello world"

    4.8 insert(pos, new_str)

            在指定位置插入新字符串。

    1. string str = "hello";
    2. str.insert(3, " there"); // str = "hello there"

    4.9 erase(start, length)

            删除指定位置的一段字符。

    1. string str = "hello world";
    2. str.erase(6, 5); // str = "hello "

    4.10 compare(str2)

      与另一个字符串比较,返回0表示相等,正数表示大于,负数表示小于。

    1. string str1 = "apple";
    2. string str2 = "banana";
    3. int result = str1.compare(str2); // result < 0,因为"apple"小于"banana"

         

    4.11 at()

            获取字符串的单个字符。

    1. string str1("hello");
    2. string str2("world");
    3. char c=str1.at(4); //获取下标为4的这个字符
    4. cout <"c ="<c <endl;
    5. str2.at(0)='h'; //更改第0个字符为'h'
    6. cout <"str2 ="<str2 <endl;

    4.12 assign()

            字符串的赋值。

    1. string str1("hello world");
    2. string str2;
    3. str2.assign(str1);
    4. cout <"str2 ="<str2 <endl;
    5. string str3;
    6. str3.assign(str1,0,5); //0开始,赋值5
    7. cout <"str3 ="<str3 <endl;

    4.13 swap()

            字符串的交换。

    1. string str1("hello");
    2. string str2("world");
    3. cout <"str1 ="<str1 <endl;
    4. cout <"str2 ="<str2 <endl;
    5. str1.swap(str2);
    6. cout <"str1 ="<str1 <endl;
    7. cout <"str2 ="<str2 <endl;

    练习1:将字符串中所有的小写字母和大写字母颠倒并输出。

    1. #include <iostream>
    2. using namespace std;
    3. int main() {
    4. string str("Hello WorLD");
    5. // 遍历字符串中的每个字符
    6. for (int i = 0; i < str.length(); ++i) {
    7. // 如果字符是大写字母,将其转换为小写字母
    8. if (str[i] >= 'A' && str[i] <= 'Z') {
    9. str[i] += 32;
    10. }
    11. // 如果字符是小写字母,将其转换为大写字母
    12. else if (str[i] >= 'a' && str[i] <= 'z') {
    13. str[i] -= 32;
    14. }
    15. }
    16. cout << str << endl;
    17. return 0;
    18. }


    练习2:编写一个程序,去掉给定字符串中重复的字符,比如goooooogle   =>    gole。

    1. #include <iostream>
    2. using namespace std;
    3. int main() {
    4. string str;
    5. cin >> str; // 从输入获取字符串,例如输入:gooooogle
    6. // 遍历字符串中的每个字符
    7. for (int i = 0; i < str.length(); ++i) {
    8. // 再次遍历字符串中的字符,从当前字符的下一个位置开始
    9. for (int j = i + 1; j < str.length(); ) {
    10. // 如果当前字符与后面的字符相同,就删除后面的字符
    11. if (str[i] == str[j]) {
    12. str.erase(j, 1); // 删除重复字符(假设删除字符的后一个还是这个字符)
    13. } else {
    14. ++j;
    15. }
    16. }
    17. }
    18. cout << str << endl; // 输出移除重复字符后的字符串
    19. return 0;
    20. }

            更多C/C++语言Linux系统数据结构ARM板实战相关文章,关注专栏:

       手撕C语言

                玩转linux

                        脚踢数据结构

                                系统、网络编程

                                         探索C++

                                                 6818(ARM)开发板实战

    📢写在最后

    • 今天的分享就到这啦~
    • 觉得博主写的还不错的烦劳 一键三连喔~
    • 🎉🎉🎉感谢关注🎉🎉🎉
  • 相关阅读:
    element-plus日历组件el-calendar自定义内容,每天绑定不同的值
    torch.manual_seed()解析
    1.7-34:回文子串
    插入排序、希尔排序
    Bilibili直播录制工具B站录播姬
    使用 Next.js、 Prisma 和 PostgreSQL 全栈开发视频网站
    Markdown博客 设置字体大小、颜色、类型等样式
    DRF-认证权限频率
    小型气象站的分类和选型要点
    施耐德电气:以服务和数字化推动可持续落地
  • 原文地址:https://blog.csdn.net/qq_64928278/article/details/132982330