当前位置:   article > 正文

C++:拼接字符串_c++ 字符串拼接

c++ 字符串拼接

 

  1. //例1.拼接字符串
  2. #include<iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. string s1 = "Hello ";
  7. string s2 = "World! ";
  8. string s3 = " China";
  9. string s4;
  10. //第一种方式:append
  11. s4.append(s1);
  12. cout << s4.c_str() << endl;
  13. s4.append(s2);
  14. cout << s4.c_str() << endl;
  15. s4.append(s3);
  16. cout << s4.c_str() << endl;
  17. //第二种方式:+
  18. s4 += " welcome!";
  19. cout << s4 << endl;
  20. s4 = s4 + "libin";
  21. cout << s4 << endl;
  22. }
  23. //例2.使用str += "a", str = str + "a" 效率差距:
  24. /*
  25. str = str + "a"加的运算产生的是一个新的对象,再把结果返回,
  26. 而str += "a" 涉及到的应该是对象的引用,操作之后直接返回引用,
  27. 避免了产生新的对象。因此,两者的性能有一定的差距。
  28. */
  29. #include <iostream>
  30. #include <string>
  31. #include<time.h>
  32. using namespace std;
  33. int main()
  34. {
  35. static int num = 500000;
  36. time_t timeBegin, timeEnd;
  37. //开始
  38. timeBegin = time(NULL);
  39. string str = "";
  40. for (int i = 0; i < num; i++)
  41. {
  42. str = str + "a";
  43. }
  44. timeEnd = time(NULL);
  45. cout << "str=str +a所耗费的时间:" << timeEnd - timeBegin << " ms" << endl;
  46. //开始
  47. timeBegin = time(NULL);
  48. string str1 = "";
  49. for (int i = 0; i < num; i++)
  50. {
  51. str1 += "a";
  52. }
  53. timeEnd = time(NULL);
  54. cout << "str+=a所耗费的时间:" << timeEnd - timeBegin << " ms" << endl;
  55. return 0;
  56. }
  57. //输出结果
  58. /*
  59. str=str +a所耗费的时间:11 ms
  60. str+=a所耗费的时间:0 ms
  61. */

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/423040
推荐阅读
相关标签
  

闽ICP备14008679号