- #include <iostream>
- #include <string>
- #include <algorithm>
- #include <sstream>
- #include <vector>
- using namespace std;
- vector<string> split(const string& src, const string sp) ;
- int main() {
- string str("Hello,World");
- //1.獲取字符串的第一個字母
- cout << "1.獲取字符串的第一個字母:" + str.substr(0, 1) << endl;
- //2.獲取字符串的第二和第三個字母
- cout << "2.獲取字符串的第二和第三個字母:" + str.substr(1, 2) << endl;
- //3.獲取字符串的最後一個字母
- cout << "3.獲取字符串的最後一個字母:" + str.substr(str.length() - 1, 1) << endl;
- //4.字符串開頭字母判斷
- if (str.find("Hello") == 0) {
- cout << "4.字符串開頭字母比較:以Hello開頭" << endl;
- }
- //5.字符串結尾字母判斷
- string w("World");
- if (str.rfind(w) == str.length() - w.length()) {
- cout << "5.字符串結尾字母比較:以World結尾" << endl;
- }
- //6.獲取字符串長度
- stringstream ss;
- ss << str.length();
- cout << "6.獲取字符串長度:" + ss.str() << endl;
- //7.大小寫轉換
- transform(str.begin(), str.end(), str.begin(), ::toupper);
- cout << "7.大小寫轉換:" + str;
- transform(str.begin(), str.end(), str.begin(), ::tolower);
- cout << "," + str << endl;
- //8.字符串轉int,int轉字符串
- int num;
- stringstream ss2("100");
- ss2 >> num;
- stringstream ss3;
- ss3 << num;
- cout << "8.字符串轉int,int轉字符串:" + ss3.str() + "," + ss3.str() << endl;
- //9.分割字符串
- vector<string> strs = ::split(str,string(","));
- cout << "9.分割字符串:[" + strs[0] +","+strs[1]<<"]"<<endl;
- //10.判斷字符串是否包含
- str="Hello,World";
- if (str.find("o,W")!=-1) {
- cout << "10.分割字符串:包含o,W" << endl;
- }
- return 0;
- }
- vector<string> split(const string& src, string sp) {
- vector<string> strs;
- int sp_len = sp.size();
- int position = 0, index = -1;
- while (-1 != (index = src.find(sp, position))) {
- strs.push_back(src.substr(position, index - position));
- position = index + sp_len;
- }
- string lastStr = src.substr(position);
- if (!lastStr.empty())
- strs.push_back(lastStr);
- return strs;
- }
String操作篇-c++
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.