{ }codelper
sorting listsP0253

Sorting sign letters

A sign shop takes down word signs and puts the letter pieces into a box in order. The first line gives the number of words n, and each of the next n lines gives one word. A word consists only of digits (0 to 9), uppercase English letters and lowercase English letters. For each word, print on its own line the string of its characters arranged from the smallest character code (ASCII) up. So every digit comes before every uppercase letter, and every uppercase letter before every lowercase letter (b, A, 9, a → 9Aab). Repeated characters are written as many times as they appear.

Input
1 ≤ n ≤ 100, word length 1 to 1,000.
Words contain only digits and uppercase and lowercase English letters
Output
n lines, each the word's characters in code order
Example 1 · stdin
3
banana
Codelper2026
ZzAa
stdout
aaabnn
0226Cdeelopr
AZaz
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

It takes three steps: turn the string into a list of characters, sort it, and join it back into a string.
Each language has a trap in the last step.
Python sorted(w) returns a list of characters, so printing it shows ['a', 'b']; join it with "".join(sorted(w)).
In Java, after char[] a = w.toCharArray(); Arrays.sort(a); convert with new String(a).
a.toString() gives text like [C@1b6d3586, and C# a.ToString() gives System.Char[] (C# uses Array.Sort(a) then new string(a)).
JS/TS use [...w].sort().join(""), but if you attach the (a, b) => a - b used for numbers, subtracting characters gives NaN and nothing moves.
For characters, sort() without a compare function already uses code order.
C++ sorts the string directly with std::sort(w.begin(), w.end()), and C sorts one-byte cells with qsort(w, strlen(w), 1, cmp).
Craykon puts the characters into a list with foreach (c in w), calls letters.Sort(); and joins with letters.Join("").
The order is code order, not dictionary order, so uppercase Z (90) comes before lowercase a (97).
Sorting while ignoring case (key=str.lower) turns ZzAa into AaZz, which is wrong.

Pythonmain.py · 5 lines
n = int(input())for _ in range(n):    w = input().strip()    # sorted(문자열)은 글자 목록을 준다 → "".join으로 다시 문자열로    print("".join(sorted(w)))
JavaScriptmain.js · 3 lines
const [n, ...words] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);// 글자끼리는 비교 함수 없이 sort()가 글자 코드 순이다console.log(words.map((w) => [...w].sort().join("")).join("\n"));
TypeScriptmain.ts · 4 lines
import { readFileSync } from "node:fs";const [n, ...words]: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const sorted: string[] = words.map((w: string) => [...w].sort().join(""));console.log(sorted.join("\n"));
JavaMain.java · 18 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Arrays; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            char[] a = in.readLine().trim().toCharArray();            Arrays.sort(a);            // char[]를 문자열로: new String(a) (a.toString()은 주소 같은 글자가 나온다)            out.append(new String(a)).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 18 lines
using System;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine().Trim());        var sb = new StringBuilder();        for (int i = 0; i < n; i++)        {            char[] a = Console.ReadLine().Trim().ToCharArray();            Array.Sort(a);   // char는 코드 순으로 정렬된다            sb.Append(new string(a)).Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 16 lines
#include <algorithm>#include <iostream>#include <string> int main() {    int n;    std::cin >> n;    std::string out;    for (int k = 0; k < n; k++) {        std::string w;        std::cin >> w;        std::sort(w.begin(), w.end());   // string은 char를 담은 목록처럼 바로 정렬된다        out += w + "\n";    }    std::cout << out;}
Cmain.c · 20 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> static int by_code(const void *pa, const void *pb) {    unsigned char a = *(const unsigned char *)pa, b = *(const unsigned char *)pb;    return (a > b) - (a < b);} int main(void) {    int n;    static char w[1024];    scanf("%d", &n);    for (int k = 0; k < n; k++) {        scanf("%1023s", w);        qsort(w, strlen(w), 1, by_code);   /* 글자 하나가 1바이트 */        puts(w);    }    return 0;}
Craykonmain.cray · 13 lines
n = Console.ReadLine().ToNumber();for (i = 0; i < n; i++){    w = Console.ReadLine().Trim();    // 문자열을 글자 목록으로 옮겨 정렬하고 다시 잇는다    글자들 = [];    foreach (c in w)    {        글자들.Add(c);    }    글자들.Sort();    Console.WriteLine(글자들.Join(""));}