#include <iostream> #include <string> #include <algorithm> using namespace std; void test01() { string s; s.assign("abcde", 4); cout << s << endl; char *p = (char*) "hello world"; s.assign(p, 10); cout << s << endl; s.assign(s, 2, 5); cout << s << endl; }
void test02() { string s = "hello world"; for (int i = 0; i < s.size(); ++i) cout << s.at(i) << " "; try { cout << s.at(100); } catch (out_of_range &e) { cout << "异常为" << e.what(); } catch (...) { cout << "捕获到其他异常"; } }
void test03() { string s = "我"; string s2 = "爱北京天安门"; s.append(s2); cout << s << endl; string s3 = "abcdefg"; int pos = s3.find("bc"); cout << pos << endl; pos = s3.find("bcf"); cout << pos << endl; pos = s3.find("bc", 2); cout << pos << endl; string s4 = "12345656"; int pos2 = s4.rfind("56",s4.size()-1 -2,1); cout << pos2 << endl; string s5 = "hello"; s5.replace(1, 3, "1111"); cout << s5;
}
void test04() { string a = "e"; string b = "H"; cout << a.compare(b); string s = "aZ"; string s2 = "ab"; cout << s.compare(s2);
s = "helloworld"; s2 = "rle"; cout << s.compare(7, 3, s2);
cout << s.compare(7, 3, s2, 0, 3); }
void test05() { string s1 ="37987244@qq.com"; string s2 = s1.substr(0, s1.find("@")); cout << s2; }
void test06() { string s1 = "hello"; s1.insert(1, "111"); cout << s1 << endl; s1.erase(1, 3); cout << s1 << endl; }
void func(string p) { cout << p << endl; }
void test07() { string s = "abc"; char t[8] = "helloo"; cout << t << endl; char *p = (char*)s.c_str(); cout << p<< endl; func(p); string s2 = p; cout << s2;
} void test08() { string s = "hello"; char &a = s[2]; char &b = s[3]; a = '1'; b = '2'; cout << s << endl << (char*)s.c_str(); s = "ppppp"; cout << a << " " << b; } int main() { test08(); }
|