c++ string 对象操作
字符串转换大小写如下:
1 #include "stdafx.h" 2 #include <iostream> 3 #include <string> 4 5 using namespace std; 6 7 int main() 8 { 9 string str = "helloworld"; 10 for (auto begin = str.begin(); begin != str.end(); ++begin) 11 { 12 *begin = toupper(*begin); 13 } 14 15 cout << str << endl; 16 17 system("PAUSE"); 18 return 0; 19 }
删除字符串中所有的大写字母:
1 #include "stdafx.h" 2 #include <iostream> 3 #include <string> 4 5 using namespace std; 6 7 int main() 8 { 9 string str("helloWorld"); 10 for (auto begin = str.begin(); begin != str.end();) 11 { 12 if (isupper(*begin)) 13 { 14 begin = str.erase(begin); 15 continue; 16 } 17 ++begin; 18 } 19 20 cout << str << endl; 21 22 23 system("PAUSE"); 24 return 0; 25 }
用vector对象初始化string :
1 #include "stdafx.h" 2 #include <iostream> 3 #include <string> 4 #include <vector> 5 6 using namespace std; 7 8 9 int main() 10 { 11 vector<char> vect; 12 char arry[] = {'h','e','l','l','o'}; 13 vect.insert(vect.begin(),arry,arry+5); 14 char *pc = new char[vect.size()+1]; 15 int i = 0; 16 for (vector<char>::iterator begin = vect.begin(); begin != vect.end(); ++begin) 17 { 18 pc[i] = *begin; 19 ++i; 20 } 21 pc[vect.size()] = '\0'; 22 string str(pc); 23 delete [] pc; 24 cout << str << endl; 25 system("PAUSE"); 26 return 0; 27 }