初始化
//string 類型的初始化方法
string s1;
string s2 = s1;
string s3 = "lol";
string s4("JarvenIV");
string s5(7,'7'); //連續n個字符組成的串
讀寫
string s;
cin>>s;
cout<<s;
范圍for語句
//c++范圍for語句,處理字符串中的每個字符
//將字符串中的每個小寫字母轉換為大寫字母
string str("I can fly high!");
for(auto &c : str) //使用引用以更改字符的值
c = toupper(c);
cout<<str<<endl;
//統計字符串中的數字個數
string s("clear4396love");
decltype(s.size()) digit_count = 0;//decltype函數返回s.size()的類型
for(auto c : s)
if(isdigit(c)) //該字符是數字
++digit_count;
cout<<digit_count;
迭代器操作
//string::const_iterator 為指向常量的迭代器類型
//string::iterator 為迭代器類型
string s("HelloWorld!");
//使用begin(),end()方法修改
for(auto i = s.begin();i != s.end();++i)
cin >> *i;
//使用cbegin(),cend()方法遍歷
for(auto i = s.cbegin();i != s.cend();++i)
cout << *i << endl;
//使用迭代器類型變量
string::const_iterator citb = s.cbegin();
string::const_iterator cite = s.cend();
string::iterator itb = s.begin();
//修改
for(auto i = itb;i != cite;++i)
cin >> *i;
//遍歷
for(auto i = citb;i != cite;++i)
cout << *i << endl;
部分操作
方法 |
功能 |
cout<<s |
輸出s |
cin>>s |
輸入s |
getline(cin,s) |
從輸入流中讀取一行賦給s |
s.empty() |
s為空則返回true |
s.size() |
返回s中字符的個數 |
s[n] |
類似c語言數組用法 |
s1+s2 |
兩個字符串連接的結果 |
s1=s2 |
將s2的值賦給s1 |
s1 == s2 |
兩個字符串完全一樣 |
s.begin() |
返回指向第一個元素的迭代器 |
s.end() |
返回指向尾元素的下一個位置的迭代器 |
s.cbegin() |
指向常量的第一個元素迭代器 |
s.cend() |
指向常量的尾后迭代器 |
string::iterator |
迭代器可以讀寫string內容 |
string::const_iterator |
迭代器只可讀,不可寫 |