题解 | #字符串排序#

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string str;
    getline(cin, str);
    string str1;
    for (int i = 0; i < str.size(); i++)//收集英语字母
    {
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
        {
            str1 += str[i];
        }
    }
    //对英语字母排序
    for (int i = 0; i < str1.size(); i++)
    {
        for (int j = 0; j < str1.size() - i - 1; j++)
        {
            if (tolower(str1[j]) > tolower(str1[j+1]))
            {
                char temp = str1[j+1];
                str1[j+1] = str1[j];
                str1[j] = temp;
            }
        }   
    }
    // 输出
    int index = 0;//英语字母排序后的字符串索引
    for (int i = 0; i < str.size(); i++)
    {
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
        {
            cout << str1[index];
            index++;
        }else{
            cout << str[i];
        }
    }
    cout << endl;
    return 0;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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