字符串排序,c++实现

字符串排序

http://www.nowcoder.com/questionTerminal/5190a1db6f4f4ddb92fd9c365c944584

基于冒泡排序

#include <iostream>
#include <string>
#include <vector>

using namespace std;
void sort(vector<char>& ch);//.adb.A

int main()
{
    string words;
    string out;
    vector<char> ch;
    while (getline(cin, words)) {
        out.clear();
        ch.clear();
        for (auto& i : words) {//将所有字母存入容器中
            if (isalpha(i)) {//判断是否为字母
                ch.push_back(i);
            }
        }
        sort(ch);
        for (int i = 0, j = 0; i < static_cast<int>(words.size()); i++) {
            if (isalpha(words[i])) {
                out += ch[j++];//字母
            }
            else {
                out += words[i];//非字母
            }
        }
        cout << out << endl;
    }
}

void sort(vector<char>& ch)//A Famous Saying: M
{
    int len = static_cast<int>(ch.size());
    for (int i = 0; i < len - 1; i++)
    {
        for (int j = 0; j < len - i - 1; j++)
        {
            if (tolower(ch[j]) > tolower(ch[j + 1]))
            {
                char temp = ch[j];
                ch[j] = ch[j + 1];
                ch[j + 1] = temp;
            }
        }
    }
}
全部评论

相关推荐

06-25 09:33
厦门大学 Java
程序员饺子:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司7个岗位
点赞 评论 收藏
分享
07-10 14:08
已编辑
江西农业大学 Java
点赞 评论 收藏
分享
宇算唯航:目测实缴资本不超100W的小公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务