首页 > 编程语言 > 详细

C++语法小记---string类

时间:2019-08-03 14:59:57      阅读:75      评论:0      收藏:0      [点我收藏+]

string类

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 // 实现字符串右移, 例子hello >> 2 ==> lohel
 7 string operator >> (const string& str, int n)
 8 {
 9     string ret = "";
10     int pos = 0;
11     
12     n = n % str.length();
13     pos = str.length() - n;
14     ret = str.substr(pos);
15     ret += str.substr(0, pos); //下标从0开始,包左不包右
16     
17     return ret;
18 }
19 
20 int main()
21 {
22     string str1 = "hello";
23     string str2 = "world";
24     
25     // 1.获取字符串长度(不包括‘\0‘)
26     cout << "str1.length = " << str1.length() << endl;
27     
28     // 2.字符串接续
29     cout << "str1 + str2 = " << str1 + str2 << endl;
30     
31     // 3.字符串遍历
32     for(int i = 0; i < str1.length(); i++)
33     {
34         cout << str1[i] << " ";
35     }
36     cout <<endl;
37     
38     for(string::iterator it = str1.begin(); it != str1.end(); it++)
39     {
40         cout << *it << " ";
41     }
42     cout <<endl;
43     
44     // 4.string转化为C语言中的char*
45     cout << "str1.c_str() = " << str1.c_str() <<endl;
46     
47     // 5.查找字符在字符串中的位置
48     cout << "str1.find(‘o‘) = " << str1.find(o) <<endl;
49     
50     // 6.截取子串
51     cout << "str1.substr(2) = " << str1.substr(2) <<endl;
52     
53     // 7.自己开发的接口
54     cout << "str1 >> 2 = " << (str1 >> 2) <<endl;
55     
56     return 0;
57 }

 

C++语法小记---string类

原文:https://www.cnblogs.com/chusiyong/p/11294783.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!