String操作編-c++



  
  
  
  
  1. #include <iostream> 
  2. #include <string> 
  3. #include <algorithm> 
  4. #include <sstream> 
  5. #include <vector> 
  6. using namespace std; 
  7. vector<string> split(const string& src, const string sp) ; 
  8. int main() { 
  9.     string str("Hello,World"); 
  10.     //1.  
  11.     cout << "1. :" + str.substr(0, 1) << endl; 
  12.     //2.  
  13.     cout << "2. :" + str.substr(1, 2) << endl; 
  14.     //3.  
  15.     cout << "3. :" + str.substr(str.length() - 1, 1) << endl; 
  16.     //4.  
  17.     if (str.find("Hello") == 0) { 
  18.         cout << "4. : Hello " << endl; 
  19.     } 
  20.     //5.  
  21.     string w("World"); 
  22.     if (str.rfind(w) == str.length() - w.length()) { 
  23.         cout << "5. : World " << endl; 
  24.     } 
  25.     //6.  
  26.     stringstream ss; 
  27.     ss << str.length(); 
  28.     cout << "6. :" + ss.str() << endl; 
  29.     //7.  
  30.     transform(str.begin(), str.end(), str.begin(), ::toupper); 
  31.     cout << "7. :" + str; 
  32.     transform(str.begin(), str.end(), str.begin(), ::tolower); 
  33.     cout << "," + str << endl; 
  34.     //8. int,int  
  35.     int num; 
  36.     stringstream ss2("100"); 
  37.     ss2 >> num; 
  38.     stringstream ss3; 
  39.     ss3 << num; 
  40.     cout << "8. int,int :" + ss3.str() + "," + ss3.str() << endl; 
  41.     //9.  
  42.     vector<string> strs = ::split(str,string(",")); 
  43.     cout << "9. :[" + strs[0] +","+strs[1]<<"]"<<endl; 
  44.     //10.  
  45.     str="Hello,World"
  46.     if (str.find("o,W")!=-1) { 
  47.         cout << "10. : o,W" << endl; 
  48.     } 
  49.     return 0; 
  50. vector<string> split(const string& src, string sp) { 
  51.     vector<string> strs; 
  52.     int sp_len = sp.size(); 
  53.     int position = 0, index = -1; 
  54.     while (-1 != (index = src.find(sp, position))) { 
  55.         strs.push_back(src.substr(position, index - position)); 
  56.         position = index + sp_len; 
  57.     } 
  58.     string lastStr = src.substr(position); 
  59.     if (!lastStr.empty()) 
  60.         strs.push_back(lastStr); 
  61.     return strs;