• <string类(上)>——《C++初阶》


    目录

    1. 为什么学习string类?

    1.1 C语言中的字符串

    1.2 两个面试题

    2. 标准库中的string类

    2.1 string类(了解)

    2.2 string类的常用接口说明(最常用的接口)

    1. string类对象的常见构造

    2. string类对象的容量操作​

    3. string类对象的访问及遍历操作

    4. string类对象的修改操作

    5. string类非成员函数 ​

    6. 题目练习:

            6.1仅仅反转字母:

            6.2找字符串中第一个只出现一次的字符​

            6.3 字符串里面最后一个单词的长度

            6.4 验证一个字符串是否是回文

            6.5 字符串相加​

    后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!                                                                    ——By 作者:新晓·故知


    GIF:

    1. 为什么学习string类?

    1.1 C语言中的字符串

    C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数, 但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。

    1.2 两个面试题

    1.2.1字符串转整形数字

    1.2.2字符串相加

    在OJ中,有关字符串的题目基本以string类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数类

    2. 标准库中的string类

    2.1 string类(了解)

    1. 字符串是表示字符序列的类
    2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
    3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信息,请参阅basic_string)。
    4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
    5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。
    总结:
    1. string是表示字符串的字符串类
    2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
    3. string在底层实际是:basic_string模板类的别名,typedef basic_stringstring;
    4. 不能操作多字节或者变长字符的序列。
    在使用string类时,必须包含#include头文件以及using namespace std;
    string是模板,只是被typedef了

     

     

     

    string的使用举例:

    1. int main()
    2. {
    3. string path = "C:\\";
    4. path += "Visual Studio2019文件夹\\";
    5. path += "C++";
    6. cout << path << endl;
    7. return 0;
    8. }

     

    1. // string constructor
    2. #include
    3. #include
    4. int main ()
    5. {
    6. std::string s0 ("Initial string");
    7. // constructors used in the same order as described above:
    8. std::string s1;
    9. std::string s2 (s0);
    10. std::string s3 (s0, 8, 3);
    11. std::string s4 ("A character sequence");
    12. std::string s5 ("Another character sequence", 12);
    13. std::string s6a (10, 'x');
    14. std::string s6b (10, 42); // 42 is the ASCII code for '*'
    15. std::string s7 (s0.begin(), s0.begin()+7);
    16. std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
    17. std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6a: " << s6a;
    18. std::cout << "\ns6b: " << s6b << "\ns7: " << s7 << '\n';
    19. return 0;
    20. }

     

    2.2 string类的常用接口说明(最常用的接口)

     1. string类对象的常见构造

      

    1. void Teststring()
    2. {
    3. string s1; // 构造空的string类对象s1
    4. string s2("hello bit"); // 用C格式字符串构造string类对象s2
    5. string s3(s2); // 拷贝构造s3
    6. }

     

     

    遍历string的每一个字符:

     

    1. //遍历string的每一个字符
    2. void TestString1()
    3. {
    4. string s1("hello");
    5. cout << s1.size() << endl; //计算字符串的size,不被包含\0
    6. //第一种遍历方式:下标+[] [是运算符重载
    7. //C++的内置类型数组可以用[]直接进行运算,但自定义类型需要通过函数重载实现
    8. //通过重载让自定义类型的使用运算,像内置类型一样简便
    9. for (size_t i = 0; i < s1.size(); i++)
    10. {
    11. cout << s1[i] << " "; //s1[i]相当于s1.operator[](i);
    12. }
    13. cout << endl;
    14. //C语言思想:
    15. /*const char* s2 = "world";
    16. s2[i]; s2[i]->*(s2+i) */
    17. //编译器根据识别的类型,(自定义类型或内置类型),调用函数重载或者对应函数
    18. //第二种遍历方式:迭代器:像指针一样的东西
    19. string::iterator it=s1.begin(); //指定类域,有可能直接定义,有可能typedef
    20. //begin 指向的是第一个数据
    21. while (it != s1.end()) //end指向的是最后字符串只读结尾的下一个位置,即\0
    22. {
    23. cout << *it << " ";
    24. ++it;
    25. }
    26. cout << endl;
    27. //第三种遍历方式:范围for 原理:编译器将其替换成迭代器
    28. //通过汇编代码可以看出
    29. for (auto ch : s1)
    30. {
    31. cout << ch << " ";
    32. }
    33. cout << endl;
    34. }
    35. int main()
    36. {
    37. TestString1();
    38. return 0;
    39. }

    2. string类对象的容量操作

    1. // size/clear/resize
    2. void Teststring1()
    3. {
    4. // 注意:string类对象支持直接用cin和cout进行输入和输出
    5. string s("hello, bit!!!");
    6. cout << s.size() << endl;
    7. cout << s.length() << endl;
    8. cout << s.capacity() << endl;
    9. cout << s << endl;
    10. // 将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
    11. s.clear();
    12. cout << s.size() << endl;
    13. cout << s.capacity() << endl;
    14. // 将s中有效字符个数增加到10个,多出位置用'a'进行填充
    15. // “aaaaaaaaaa”
    16. s.resize(10, 'a');
    17. cout << s.size() << endl;
    18. cout << s.capacity() << endl;
    19. // 将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
    20. // "aaaaaaaaaa\0\0\0\0\0"
    21. // 注意此时s中有效字符个数已经增加到15个
    22. s.resize(15);
    23. cout << s.size() << endl;
    24. cout << s.capacity() << endl;
    25. cout << s << endl;
    26. // 将s中有效字符个数缩小到5个
    27. s.resize(5);
    28. cout << s.size() << endl;
    29. cout << s.capacity() << endl;
    30. cout << s << endl;
    31. }
    32. //====================================================================================
    33. void Teststring2()
    34. {
    35. string s;
    36. // 测试reserve是否会改变string中有效元素个数
    37. s.reserve(100);
    38. cout << s.size() << endl;
    39. cout << s.capacity() << endl;
    40. // 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
    41. s.reserve(50);
    42. cout << s.size() << endl;
    43. cout << s.capacity() << endl;
    44. }
    45. // 利用reserve提高插入数据的效率,避免增容带来的开销
    46. //====================================================================================
    47. void TestPushBack()
    48. {
    49. string s;
    50. size_t sz = s.capacity();
    51. cout << "making s grow:\n";
    52. for (int i = 0; i < 100; ++i)
    53. {
    54. s.push_back('c');
    55. if (sz != s.capacity())
    56. {
    57. sz = s.capacity();
    58. cout << "capacity changed: " << sz << '\n';
    59. }
    60. }
    61. }
    62. void TestPushBackReserve()
    63. {
    64. string s;
    65. s.reserve(100);
    66. size_t sz = s.capacity();
    67. cout << "making s grow:\n";
    68. for (int i = 0; i < 100; ++i)
    69. {
    70. s.push_back('c');
    71. if (sz != s.capacity())
    72. {
    73. sz = s.capacity();
    74. cout << "capacity changed: " << sz << '\n';
    75. }
    76. }
    77. }

    注意:
    1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
    2. clear()只是将string中有效字符清空,不改变底层空间大小。
    3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
    4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。

    3. string类对象的访问及遍历操作

    iterator:
    1. void Teststring()
    2. {
    3. string s1("hello Bit");
    4. const string s2("Hello Bit");
    5. cout << s1 << " " << s2 << endl;
    6. cout << s1[0] << " " << s2[0] << endl;
    7. s1[0] = 'H';
    8. cout << s1 << endl;
    9. // s2[0] = 'h'; 代码编译失败,因为const类型对象不能修改
    10. }
    11. void Teststring()
    12. {
    13. string s("hello Bit");
    14. // 3种遍历方式:
    15. // 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符,
    16. // 另外以下三种方式对于string而言,第一种使用最多
    17. // 1. for+operator[]
    18. for (size_t i = 0; i < s.size(); ++i)
    19. cout << s[i] << endl;
    20. // 2.迭代器
    21. string::iterator it = s.begin();
    22. while (it != s.end())
    23. {
    24. cout << *it << endl;
    25. ++it;
    26. }
    27. string::reverse_iterator rit = s.rbegin();
    28. while (rit != s.rend())
    29. cout << *rit << endl;
    30. // 3.范围for
    31. for (auto ch : s)
    32. cout << ch << endl;
    33. }

    1. //迭代器:4种
    2. void TestString2()
    3. {
    4. string s1("hello");
    5. //1.正向迭代器
    6. string::iterator it = s1.begin(); //指定类域,有可能直接定义,有可能typedef
    7. //begin 指向的是第一个数据
    8. while (it != s1.end()) //end指向的是最后字符串只读结尾的下一个位置,即\0
    9. {
    10. cout << *it << " ";
    11. ++it;
    12. }
    13. cout << endl;
    14. //2.反向迭代器
    15. string::reverse_iterator rit = s1.rbegin();
    16. while (rit != s1.rend())
    17. {
    18. cout << *rit << " ";
    19. ++rit;
    20. }
    21. cout << endl;
    22. }
    23. int main()
    24. {
    25. TestString2();
    26. return 0;
    27. }

     

    1. //迭代器:4种
    2. void Func(const string& s)
    3. {
    4. //正向只读迭代器
    5. string::const_iterator it = s.begin();
    6. while (it != s.end())
    7. {
    8. cout << *it << " ";
    9. ++it;
    10. }
    11. cout << endl;
    12. //反向只读迭代器
    13. string::const_reverse_iterator rit = s.rbegin();
    14. while (rit != s.rend())
    15. {
    16. cout << *rit << " ";
    17. ++rit;
    18. }
    19. cout << endl;
    20. }
    21. void TestString3()
    22. {
    23. string s1("hello");
    24. //正向迭代器、反向迭代器可以读写,遇到只能读权限的情况就需要只读迭代器
    25. Func(s1);
    26. cout << endl;
    27. }
    28. int main()
    29. {
    30. TestString3();
    31. return 0;
    32. }

    lenth和size:

     capacity:

    4. string类对象的修改操作

    注意:
    1. 在string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差不多,一般 情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
    2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。
    扩空间:(尾插版)

    1. void TestPushBack()
    2. {
    3. string s;
    4. cout << s.capacity() << endl;
    5. size_t sz = s.capacity();
    6. cout << "making s grow:\n";
    7. for (int i = 0; i < 200; ++i)
    8. {
    9. s.push_back('c');
    10. if (sz != s.capacity())
    11. {
    12. sz = s.capacity();
    13. cout << "capacity changed: " << sz << '\n';
    14. }
    15. }
    16. }
    17. int main()
    18. {
    19. TestPushBack();
    20. return 0;
    21. }

    reserve:

    resize:

    insert:头插

    insert插入字符:

     

    1. void TestString1()
    2. {
    3. string s1("hello");
    4. s1.insert(0, 1, 'x'); //在第一个位置插入数据
    5. cout << s1 << endl;
    6. s1.insert(3, 1, 'y'); //在第3个位置插入数据
    7. cout << s1 << endl;
    8. s1.insert(2, 1, 'x');
    9. s1.insert(s1.begin() + 2, 'q'); //在第2个位置通过迭代器插入数据
    10. cout << s1 << endl;
    11. }
    12. int main()
    13. {
    14. TestString1();
    15. return 0;
    16. }

     insert插入字符串:

    erase:

     

    1. //erase
    2. void TestString3()
    3. {
    4. string s1("hello,world");
    5. s1.erase(s1.begin()); //通过使用迭代器头删
    6. cout << s1 << endl;
    7. s1.erase(s1.begin()+3); //通过使用迭代器删除指定位置
    8. cout << s1 << endl;
    9. s1.erase(3,2); //第3个位置后删除n个
    10. cout << s1 << endl;
    11. }
    12. int main()
    13. {
    14. TestString3();
    15. return 0;
    16. }

     swap:

    1. //swap
    2. void TestString3()
    3. {
    4. string s1("hello,world");
    5. string s2("string");
    6. //C++98中
    7. s1.swap(s2); //string中的swap,交换指针,效率高
    8. //swap(s1, s2); //STL中的swap,是全局的,可交换任意类型,深拷贝交换,代价大,效率低
    9. cout << s1 << endl;
    10. cout << s2 << endl;
    11. }
    12. int main()
    13. {
    14. TestString3();
    15. return 0;
    16. }

     find:

    1. //find
    2. void TestString4()
    3. {
    4. // 获取file的后缀
    5. string file("string.cpp");
    6. size_t pos = file.find('.'); //正着找
    7. if (pos != string::npos)
    8. {
    9. string suffix(file.substr(pos, file.size() - pos));
    10. //string suffix(file.substr(pos)); 单个形参,有多少取多少
    11. cout << file << "后缀:" << suffix << endl;
    12. }
    13. else
    14. {
    15. cout << "没有后缀" << endl;
    16. }
    17. }
    18. int main()
    19. {
    20. TestString4();
    21. return 0;
    22. }

     反着找:

     利用string对网址操作:

    1. void TestString5()
    2. {
    3. // 取出url中的域名
    4. string url("http://www.cplusplus.com/reference/string/string/find/");
    5. cout << url << endl;
    6. string protocol; //协议
    7. size_t pos1 = url.find("://");
    8. if (pos1!= string::npos)
    9. {
    10. protocol = url.substr(0, pos1);
    11. cout << "protocol:"<
    12. }
    13. else
    14. {
    15. cout << "未找到协议,非法url" << endl;
    16. }
    17. string domain; //取出域名
    18. size_t pos2 = url.find('/',pos1+3);
    19. if (pos2 != string::npos)
    20. {
    21. domain = url.substr(pos1+3, pos2-(pos1+3));
    22. cout << "domain:" << domain << endl;
    23. }
    24. string uri; //资源
    25. uri = url.substr(pos2 + 1);
    26. cout << "uri:" << uri << endl;
    27. // 删除url的协议前缀
    28. pos1 = url.find("://");
    29. url.erase(0, pos1 + 3);
    30. cout << url << endl;
    31. }
    32. int main()
    33. {
    34. TestString5();
    35. return 0;
    36. }

     5. string类非成员函数 

    上面的几个接口了解一下,下面的OJ题目中会有一些体现它们的使用。string类中还有一些其他的操作,这里不一一列举,在需要用到时不明白了查文档即可。

    6. 题目练习:

    6.1仅仅反转字母:

    1. class Solution {
    2. public:
    3. //判断是否为字符
    4. bool isLetter(char ch)
    5. {
    6. if(ch>='a'&&ch<='z')
    7. return true;
    8. else if(ch>='A'&&ch<='Z')
    9. return true;
    10. else
    11. return false;
    12. }
    13. string reverseOnlyLetters(string s) {
    14. int left=0,right=s.size()-1;
    15. while(left
    16. {
    17. while(leftisLetter(s[left]))
    18. ++left;
    19. while(leftisLetter(s[right]))
    20. --right;
    21. swap(s[left],s[right]);
    22. ++left;
    23. --right;
    24. }
    25. return s;
    26. }
    27. };

    6.2找字符串中第一个只出现一次的字符

    1. class Solution {
    2. public:
    3. int firstUniqChar(string s) {
    4. int count[26]={0};
    5. //统计次数
    6. for(auto ch : s)
    7. {
    8. count[ch-'a']++;
    9. }
    10. for(size_t i=0;isize();++i)
    11. {
    12. if(count[s[i]-'a']==1)
    13. {
    14. return i;
    15. }
    16. }
    17. return -1;
    18. }
    19. };

    6.3 字符串里面最后一个单词的长度

    1. #include
    2. #include
    3. using namespace std;
    4. int main()
    5. {
    6. string str;
    7. //cin>>str; 缓存区的空格会干扰读取
    8. getline(cin, str);
    9. size_t pos = str.rfind(' ');
    10. if (pos != string::npos)
    11. {
    12. cout << str.size() - pos - 1 << endl;
    13. }
    14. else
    15. {
    16. cout << str.size() << endl;
    17. }
    18. return 0;
    19. }

     6.4 验证一个字符串是否是回文:

    1. class Solution
    2. {
    3. public:
    4. bool isLetterOrNumber(char ch)
    5. {
    6. return (ch >= '0' && ch <= '9')
    7. || (ch >= 'a' && ch <= 'z')
    8. || (ch >= 'A' && ch <= 'Z');
    9. }
    10. bool isPalindrome(string s) {
    11. // 先小写字母转换成大写,再进行判断
    12. for (auto& ch : s)
    13. {
    14. if (ch >= 'a' && ch <= 'z')
    15. ch -= 32;
    16. }
    17. int begin = 0, end = s.size() - 1;
    18. while (begin < end)
    19. {
    20. while (begin < end && !isLetterOrNumber(s[begin]))
    21. ++begin;
    22. while (begin < end && !isLetterOrNumber(s[end]))
    23. --end;
    24. if (s[begin] != s[end])
    25. {
    26. return false;
    27. }
    28. else
    29. {
    30. ++begin;
    31. --end;
    32. }
    33. }
    34. return true;
    35. }
    36. };

    6.5 字符串相加

    1. class Solution
    2. {
    3. public:
    4. string addStrings(string num1, string num2)
    5. {
    6. int end1 = num1.size() - 1;
    7. int end2 = num2.size() - 1;
    8. int carry = 0;
    9. string retStr;
    10. while(end1 >= 0 || end2 >= 0)
    11. {
    12. int val1 = end1 >= 0 ? num1[end1] - '0' : 0;
    13. int val2 = end2 >= 0 ? num2[end2] - '0' : 0;
    14. int ret = val1 + val2 + carry;
    15. if (ret > 9)
    16. {
    17. ret -= 10;
    18. carry = 1;
    19. }
    20. else
    21. {
    22. carry = 0;
    23. }
    24. //retStr.insert(retStr.begin(),'0'+ret); //效率低
    25. retStr += ('0' + ret);
    26. --end1;
    27. --end2;
    28. }
    29. if (carry == 1)
    30. retStr += '1';
    31. reverse(retStr.begin(), retStr.end());
    32. return retStr;
    33. }
    34. };

    后记:
    ●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!
                                                                        ——By 作者:新晓·故知

  • 相关阅读:
    Nacos适配达梦
    LLaMA-Adapter源码解析
    Acwing 3302. 表达式求值
    如何将PDF转成Word文档?这里有你想要的答案
    sealos 与其它流行产品的差异与联系
    react处理跨域
    Flink写入kafka的自定义Key值
    CTF--攻防世界--杂项基础
    java计算机毕业设计web考试资料交易系统设计与实现源码+mysql数据库+系统+lw文档+部署
    IS420ESWBH3A GE 附加配置文件和I/O组件中的单独标签
  • 原文地址:https://blog.csdn.net/m0_57859086/article/details/126089128