卑微的C++程序员怎么分割子串

卑微的C++程序员怎么分割字串

#include
using namespace std;
vector<string> split(const string &str, const string &pattern)
{
    vector<string> res;
    if(str == "")
        return res;
    //在字符串末尾也加入分隔符,方便截取最后一段
    string strs = str + pattern;
    size_t pos = strs.find(pattern);

    while(pos != strs.npos)
    {
        string temp = strs.substr(0, pos);
        toupper(temp[0]);
        res.push_back(temp);
        //去掉已分割的字符串,在剩下的字符串中进行分割
        strs = strs.substr(pos+1, strs.size());
        pos = strs.find(pattern);
    }

    return res;
}
int main(){
    string str;
    cin >> str;
    vector<string> vec;
    vec = split(str,"n");
    for (int i = 0; i < vec.size(); ++i) {
        if(i == 0 && vec[i] != ""){
            //char ch = vec[i][0];
            vec[i][0] = vec[i][0] - 32;
            cout<<vec[i]<<endl;
        }
        else if(vec[i] == ""){
            continue;
        }
        else{
            cout<<"N" + vec[i]<<endl;
        }
    }
}

PS:处理字符串常见题型需要掌握啊。

你可能感兴趣的:(笔试)