链接:https://ac.nowcoder.com/acm/contest/5657/I
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
对输入的字符串进行排序后输出
打开以下链接可以查看正确的代码
https://ac.nowcoder.com/acm/contest/5657#question

输入描述:
多个测试用例,每个测试用例一行。

每行通过空格隔开,有n个字符,n<100
输出描述:
对于每组测试用例,输出一行排序过的字符串,每个字符串通过空格隔开
示例1
输入
复制
a c bb
f dddd
nowcoder
输出
复制
a bb c
dddd f
nowcoder

思路和心得

1.c++

(1) getline(cin, line)

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

int main()
{
    string line;
    while (getline(cin, line))
    {
        stringstream ss;    ss << line;
        vector<string> words;
        string word;
        while (ss >> word)
            words.push_back(word);

        sort(words.begin(), words.end());
        for (string word : words)
            cout <<  word << ' ';
        cout << endl;
    }

    return 0;
}

(2) 也可以通过判断换行符 cin.get() == '\n'

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

int main()
{
    vector<string> words;
    string word;
    while (cin >> word)
    {
        words.push_back(word);
        if (cin.get() == '\n')
        {

            sort(words.begin(), words.end());
            for (string word : words)
                cout <<  word << ' ';
            cout << endl;

            words.clear();    //清空
        }
    }

    return 0;
}

(3) 或者getchar() == '\n'

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

int main()
{
    vector<string> words;
    string word;
    while (cin >> word)
    {
        words.push_back(word);
        if (getchar() == '\n')
        {

            sort(words.begin(), words.end());
            for (string word : words)
                cout <<  word << ' ';
            cout << endl;

            words.clear();    //清空
        }
    }

    return 0;
}

2.python3 [x for x in input().split()] 千年不变

while True:
    try:
        words = [x for x in input().split()]
        words.sort()
        for word in words:
            print(word, end = ' ')
        print()
    except:
        break

3.java

import java.util.* ;

public class Main
{
    public static void main(String [] args)
    {
        Scanner scan = new Scanner(System.in);

        while (scan.hasNextLine())
        {
            String [] words = scan.nextLine().split(" ");
            Arrays.sort(words);
            for (String word : words)
                System.out.print(word + " ");
            System.out.println();
        }
    }

}