C++语法小记---string类
发布时间:2020-12-16 10:47:40 所属栏目:百科 来源:网络整理
导读: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 = s
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.获取字符串长度(不包括‘ ‘) 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |