华为机试---简单字符串分割题

在这里插入图片描述
字符串分割题
可以使用stringstream的简便方法来做

#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    string s;
    while(getline(cin,s)){
        int len = s.size();
        for(int i = 0;i < len;++i){
            if(!isalpha(s[i])){
                s[i] = ' ';
            }
        }
        stringstream ss;
        ss << s;
        string tmp;
        vector<string>ve;
        while(ss >> tmp){
            ve.push_back(tmp);
        }
        for(int i = ve.size() - 1;i >= 0;--i){
            if(i == 0){
                cout << ve[i] << endl;
            }else{
                cout << ve[i] << " ";
            }
        }
    }
    return 0;
}

自己手动实现的字符串分割

#include<bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    while(getline(cin,s)){
        int len = s.size();
        string tmp;
        vector<string>ve;
        for(int i = 0;i < len;++i){
            if((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')){
                tmp += s[i];
            }else{
                if(tmp.size() > 0){
                    ve.push_back(tmp);
                    tmp.clear();
                }
            }
        }
        if(tmp.size() > 0){
            ve.push_back(tmp);
        }
        for(int i = ve.size() - 1;i >= 0;--i){
            if(i == 0){
                cout << ve[i] << endl;
            }else{
                cout << ve[i] << " ";
            }
        }
    }
    return 0;
}
发布了269 篇原创文章 · 获赞 33 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36386435/article/details/100152492