• string类的常用接口说明


    STL六大组件:

    容器 

    算法

    配接器

    迭代器

    仿函数

    空间配置器

    温馨提示:只讲常用接口,使用方法说明详见代码注释

    目录

    一、string类对象的常见构造

    二、string类对象的容量操作

    三、类对象的访问及遍历操作

    四、string类对象的修改操作

    五、string类非成员函数

    六、汇总代码


    一、string类对象的常见构造

    1. #include<iostream>
    2. using namespace std;
    3. #include<string>
    4. //typedef basic_string<char16_t> u16string;
    5. std::string s0("Initial string");
    6. //构造空的string类对象,即空字符串(默认构造)
    7. //default (1) explicit basic_string(const allocator_type& alloc = allocator_type());
    8. std::string s1;
    9. //用C-string来构造string类对象
    10. //copy(2) basic_string(const basic_string& str);
    11. std::string s2(s0);
    12. //拷贝构造函数
    13. //copy(2) basic_string(const basic_string& str);
    14. std::string s2(s0);
    15. void Teststring()
    16. {
    17. string s1;//构造空的string类对象s1
    18. string s2("hello sunlang");//用C格式字符串构造string类对象s2
    19. string s3(s2);//拷贝构造s3
    20. }

    二、string类对象的容量操作

    1. //返回字符串有效字符长度
    2. //size_type size() const;
    3. int main()
    4. {
    5. std::string str("Test string");
    6. std::cout << "The size of str is" << str.size() << "characters.\n";
    7. return 0;
    8. }
    1. //检测字符串释放为空串,是返回true,否则返回false
    2. //bool empty() const;
    3. int main()
    4. {
    5. std::string content;
    6. std::string line;
    7. std::cout << "Please introduce a text.Enter an empty line to finish:\n";
    8. do
    9. {
    10. getline(std::cin, line);
    11. content += line + '\n';
    12. } while (!line.empty());
    13. std::cout << "The text you introduced was:\n" << content;
    14. return 0;
    15. }
    1. //清空有效字符
    2. //void clear();
    3. int main()
    4. {
    5. char c;
    6. std::string str;
    7. std::cout << "Please type some lines of text. Enter a dot (.) to finish:\n";
    8. do {
    9. c = std::cin.get();
    10. str += c;
    11. if (c == '\n')
    12. {
    13. std::cout << str;
    14. str.clear();
    15. }
    16. } while (c != '.');
    17. return 0;
    18. }
    1. //为字符串预留空间**
    2. //void reserve (size_type n = 0);
    3. int main()
    4. {
    5. std::string str;
    6. std::ifstream file("test.txt", std::ios::in | std::ios::ate);
    7. if (file) {
    8. std::ifstream::streampos filesize = file.tellg();
    9. str.reserve(filesize);
    10. file.seekg(0);
    11. while (!file.eof())
    12. {
    13. str += file.get();
    14. }
    15. std::cout << str;
    16. }
    17. return 0;
    18. }
    1. //将有效字符的个数改成n个,多出的空间用字符C填充
    2. //void resize (size_type n);
    3. //void resize(size_type n, charT c)
    4. int main()
    5. {
    6. std::string str("I like to code in C");
    7. std::cout << str << '\n';
    8. std::string::size_type sz = str.size();
    9. str.resize(sz + 2, '+');
    10. std::cout << str << '\n';
    11. str.resize(14);
    12. std::cout << str << '\n';
    13. return 0;
    14. }

    三、类对象的访问及遍历操作

    1. //返回pos位置的字符,const string类对象调用
    2. //reference operator[] (size_type pos);
    3. //const_reference operator[] (size_type pos) const;
    4. int main()
    5. {
    6. std::string str("Test string");
    7. for (int i = 0; i < str.length(); ++i)
    8. {
    9. std::cout << str[i];
    10. }
    11. return 0;
    12. }

    四、string类对象的修改操作

    1. //在字符串后面追加字符串str
    2. //string(1)
    3. //basic_string& operator+= (const basic_string& str);
    4. //c - string(2)
    5. //basic_string & operator+= (const charT * s);
    6. //character(3)
    7. //basic_string& operator+= (charT c);
    8. int main()
    9. {
    10. std::string name("John");
    11. std::string family("Smith");
    12. name += "K"; // c-string
    13. name += family; // string
    14. name += '\n'; // character
    15. std::cout << name;
    16. return 0;
    17. }
    1. //返回C格式字符串
    2. //const charT* c_str() const;
    3. int main()
    4. {
    5. std::string str("Please split this sentence into tokens");
    6. char* cstr = new char[str.length() + 1];
    7. std::strcpy(cstr, str.c_str());
    8. // cstr now contains a c-string copy of str
    9. char* p = std::strtok(cstr, " ");
    10. while (p != 0)
    11. {
    12. std::cout << p << '\n';
    13. p = strtok(NULL, " ");
    14. }
    15. delete[] cstr;
    16. return 0;
    17. }
    1. //从字符串pos位置开始往后找字符C,返回该字符在字符串中的位置
    2. //string(1)
    3. //size_type find(const basic_string& str, size_type pos = 0) const;
    4. //c - string(2)
    5. //size_type find(const charT * s, size_type pos = 0) const;
    6. //buffer(3)
    7. //size_type find(const charT* s, size_type pos, size_type n) const;
    8. //character(4)
    9. //size_type find(charT c, size_type pos = 0) const;
    10. int main()
    11. {
    12. std::string str("There are two needles in this haystack with needles.");
    13. std::string str2("needle");
    14. // different member versions of find in the same order as above:
    15. std::string::size_type found = str.find(str2);
    16. if (found != std::string::npos)
    17. std::cout << "first 'needle' found at: " << found << '\n';
    18. found = str.find("needles are small", found + 1, 6);
    19. if (found != std::string::npos)
    20. std::cout << "second 'needle' found at: " << found << '\n';
    21. found = str.find("haystack");
    22. if (found != std::string::npos)
    23. std::cout << "'haystack' also found at: " << found << '\n';
    24. found = str.find('.');
    25. if (found != std::string::npos)
    26. std::cout << "Period found at: " << found << '\n';
    27. // let's replace the first needle:
    28. str.replace(str.find(str2), str2.length(), "preposition");
    29. std::cout << str << '\n';
    30. return 0;
    31. }

    五、string类非成员函数

    1. //输入运算符重载
    2. //template <class charT, class traits, class Alloc>
    3. //basic_istream<charT, traits>& operator>> (basic_istream& is,
    4. // basic_string<charT, traits, Alloc>& str);
    5. int main()
    6. {
    7. std::string name;
    8. std::cout << "Please, enter your name: ";
    9. std::cin >> name;
    10. std::cout << "Hello, " << name << "!\n";
    11. return 0;
    12. }
    1. //输出运算符重载
    2. //template <class charT, class traits, class Alloc>
    3. //basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& os,
    4. // const basic_string<charT, traits, Alloc>& str);
    5. int main()
    6. {
    7. std::string str = "Hello world!";
    8. std::cout << str << '\n';
    9. return 0;
    10. }
    1. //获取一行字符串
    2. //template <class charT, class traits, class Alloc>
    3. //1)basic_istream<charT, traits>& getline(basic_istream<charT, traits>& is,
    4. // basic_string<charT, traits, Alloc>& str, charT delim);
    5. //(2)
    6. //template <class charT, class traits, class Alloc>
    7. //basic_istream<charT, traits>& getline(basic_istream<charT, traits>& is,
    8. // basic_string<charT, traits, Alloc>& str);
    9. int main()
    10. {
    11. std::string name;
    12. std::cout << "Please, enter your full name: ";
    13. std::getline(std::cin, name);
    14. std::cout << "Hello, " << name << "!\n";
    15. return 0;
    16. }
    1. //大小比较
    2. int main()
    3. {
    4. std::string foo = "alpha";
    5. std::string bar = "beta";
    6. if (foo == bar) std::cout << "foo and bar are equal\n";
    7. if (foo != bar) std::cout << "foo and bar are not equal\n";
    8. if (foo < bar) std::cout << "foo is less than bar\n";
    9. if (foo > bar) std::cout << "foo is greater than bar\n";
    10. if (foo <= bar) std::cout << "foo is less than or equal to bar\n";
    11. if (foo >= bar) std::cout << "foo is greater than or equal to bar\n";
    12. return 0;
    13. }

    六、汇总代码

    1. #include
    2. using namespace std;
    3. #include
    4. //测试string容量相关的接口
    5. //size/clear/resize
    6. void Teststring1()
    7. {
    8. //注意:string类对象支持直接用cin和cout进行输入和输出
    9. string s("hello,sunlang!!!");//用C-siring来构造string类对象
    10. cout << s.size() << endl;//返回字符串有效字符长度
    11. cout << s.length() << endl;//返回字符串有效字符长度
    12. cout << s.capacity() << endl;//返回空间总大小
    13. cout << s << endl;
    14. //将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
    15. s.clear();
    16. cout << s.size() << endl;
    17. cout << s.capacity() << endl;
    18. //将s中有效字符个数增加到10个,多出位置用‘a'进行补充
    19. //"aaaaaaaa"
    20. s.resize(10, 'a');
    21. cout << s.size() << endl;
    22. cout << s << endl;
    23. cout << s.capacity() << endl;
    24. //将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行补充
    25. //"aaaaaaaa\0\0\0\0"
    26. s.resize(15);
    27. cout << s.size() << endl;
    28. cout << s.capacity() << endl;
    29. cout << s << endl;
    30. //将s中有效字符个数缩小到5个
    31. s.resize(5);
    32. cout << s.size() << endl;
    33. cout << s.capacity() << endl;
    34. cout << s << endl;
    35. }
    36. void Teststring2()
    37. {
    38. string s;
    39. //测试reserve是否会改变string中有效元素个数
    40. s.reserve(100);
    41. cout << s.size() << endl;
    42. cout << s.capacity() << endl;
    43. //测试reserve参数小于string的底层空间大小时,是否会将空间缩小
    44. s.reserve(50);
    45. cout << s.size() << endl;
    46. cout<capacity()<
    47. }
    48. //利用reserve提高插入数据的效率,避免增容带来的开销
    49. void TestPushBack()
    50. {
    51. string s;
    52. size_t sz = s.capacity();
    53. cout << "making s grow:\n";
    54. for (int i = 0; i < 100; ++i)
    55. {
    56. s.push_back('c');
    57. if (sz != s.capacity())
    58. {
    59. sz = s.capacity();
    60. cout << "capacity changed:" << sz << '\n';
    61. }
    62. }
    63. }
    64. //构建vector时,如果提前已经知道string中大概要放多少个元素,可以提前将string中空间设置好
    65. void TestPushBackReserve()
    66. {
    67. string s;
    68. s.reserve(100);
    69. size_t sz = s.capacity();
    70. cout << "making s grow:\n";
    71. for (int i = 0; i < 100; ++i)
    72. {
    73. s.push_back('c');
    74. if (sz != s.capacity())
    75. {
    76. sz = s.capacity();
    77. cout << "capacity changed:" << sz << '\n';
    78. }
    79. }
    80. }
    81. //string的遍历
    82. //begin()+end() for+[] 范围for
    83. //注意:string遍历时使用最多的还是for+下标或者范围for(C++11后才支持)
    84. //begin()+end()大多数使用在需要使用STL提供的算法操作string时,比如:采用reserve逆置string
    85. void Teststring3()
    86. {
    87. string s1("hello sunlang");
    88. const string s2("Hello sunlang");
    89. cout << s1 << " " << s2 << endl;
    90. cout << s1[0] << " " << s2[0] << endl;
    91. s1[0] = 'H';
    92. cout << s1 << endl;
    93. //s2[0]='h';代码编译失败,因为const类型对象不能修改
    94. }
    95. void Teststring4()
    96. {
    97. string s("hello sunlang");
    98. //以下三种方式除了遍历string对象,还可以遍历修改string中的字符
    99. //第一种使用最多
    100. //for+operator[]
    101. for (size_t i = 0; i < s.size(); ++i)
    102. {
    103. cout << s[i] << endl;
    104. }
    105. //迭代器
    106. string::iterator it = s.begin();
    107. while (it != s.end())
    108. {
    109. cout << *it << endl;
    110. ++it;
    111. }
    112. //string::reserve_iterator rit =s.rbegin();
    113. //C++11之后,直接使用auto定义迭代器,让编译器推到迭代器的类型
    114. //auto rit = s.rbegin();
    115. //while (rit != s.rend())
    116. //{
    117. // cout << *rit << endl;
    118. //}
    119. //范围for
    120. for (auto ch : s)
    121. {
    122. cout << ch << endl;
    123. }
    124. }
    125. //测试string
    126. //1、插入(拼接)方式:push_back append operator+=
    127. //2、正向和反向查找:find()+rfind()
    128. //3、截取子串:substr()
    129. //4、删除:erase
    130. void Teststring5()
    131. {
    132. string str;
    133. str.push_back(' ');//在str后插入空格
    134. str.append("hello");//在str后追加一个字符"hello"
    135. str += 's';//在str后追加一个字符'b'
    136. str += "un";//在str后追加一个字符串"it"
    137. cout << str << endl;
    138. cout << str.c_str() << endl;//以C语言的方式打印字符串
    139. //获取file的后缀
    140. string file("Test.cpp");
    141. size_t pos = file.rfind('.');
    142. string suffix(file.substr(pos, file.size() - pos));
    143. cout << suffix << endl;
    144. //npos是string里面的一个静态成员变量
    145. //static const size_t npos=-1;
    146. //取出ur1中的域名
    147. string ur1("https://mp.csdn.net/mp_blog/creation/editor/128085730");
    148. cout << ur1 << endl;
    149. size_t start = ur1.find("://");
    150. if (start == string::npos)
    151. {
    152. cout << "invalid url" << endl;
    153. return;
    154. }
    155. start += 3;
    156. size_t finish = url.find('/', start);
    157. string address = url.substr(start, finish - start);
    158. cout << address << endl;
    159. // 删除 url 的协议前缀
    160. pos = url.find("://");
    161. url.erase(0, pos + 3);
    162. cout << url << endl;
    163. }
    164. int main()
    165. {
    166. Teststring1();
    167. Teststring2();
    168. TestPushBack();
    169. TestPushBackReserve();
    170. Teststring3();
    171. Teststring4();
    172. Teststring5();
    173. return 0;
    174. }

  • 相关阅读:
    高速信号处理板资料保存:383-基于kintex UltraScale XCKU060的双路QSFP+光纤PCIe 卡设计原理图
    4. 运行Openocd
    java 实现布隆过滤器(BloomFilter)
    Jenkins共享库使用
    03 Linux
    OpenLayers实战,WebGL图层根据Feature要素的变量动态渲染多种颜色的三角形,适用于大量三角形渲染不同颜色
    Java高级:网络编程
    400 The plain HTTP request was sent to HTTPS port
    ardupilot开发 --- 通信链路 篇
    biquad滤波器的设计
  • 原文地址:https://blog.csdn.net/lang_965/article/details/128085730