当前位置:编程学习 > C/C++ >>

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;
}
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,