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; 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章