String操作編-c++
- #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;
- }