Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write a program that takes a string and outputs all the characters in alphabetical order. Spaces and symbols can be ignored or deleted, but the upper- and lowercase letters must remain the same case.

Sample input:

Johnny walked the dog to the park.

Sample output

aaddeeeghhhJklnnoooprtttwy

Rules:

• Any language

• Shortest code wins.

share|improve this question
3  
How to sort upper/lower case letters? Upper before lower, vice versa or stable with the input? –  Howard Jan 22 at 8:51
    
Does it need to handle any letters outside of the basic Latin alphabet ("English alphabet")? –  Sebastian Negraszus Jan 22 at 11:02
    
From the title, I was hoping I could get away with displaying "Sentence in Alphabetical Order". Or "ceeennst". (OK, "Sceeennt", if you insist on correct capitalization and ASCII order.) –  keshlam Jan 22 at 16:16
    
I'm tempted to post print "all the characters in alphabetical order" :-P –  Doorknob Jan 22 at 17:56
1  
Youre missing a D in your sample output :P –  Teun Pronk Jan 31 at 13:28
show 1 more comment

17 Answers 17

up vote 10 down vote accepted

GolfScript, 24 / 6 characters

{26,{65+.32+}%?)},{31&}$

Example:

> Johnny walked the dog to the park.
aaddeeeghhhJkklnnoooprtttwy  

If the input is restricted to printable ascii the code can be shortened by three characters using {95&.64>\91<&}, as filter.

Can be tested here.

The can-be-ignored version is even shorter (6 chars):

{31&}$

and yields output

> Johnny walked the dog to the park.
      aaddeeeghhhJkkl.nnoooprtttwy
share|improve this answer
    
and if "alphabetize" could be construed to mean "ASCII order okay, it could just be reduced to {}$ –  McKay Jan 29 at 16:33
    
@McKay The question explicitely states differently. And {}$ would be equivalent to $. –  Howard Jan 29 at 16:56
    
Oh, yeah. Thanks, I'm trying to learn golfscript –  McKay Jan 29 at 17:16
add comment

GNU core utils - 25 characters (29 dropping symbols)

fold -1|sort -f|tr -d \\n

Example (from GNU bash 3):

$ echo "Johnny walked the dog to the park."|fold -1|sort -f|tr -d \\n
      .aaddeeeghhhJkklnnoooprtttwy   <<no trailing newline>>

From the question:

Spaces and symbols can be ignored or deleted

I chose to leave them in! To retain only alphabetic characters, replace fold -1 with grep -o \\w for +4 characters.

grep -o \\w|sort -f|tr -d \\n

Thanks to Firefly for recommending grep -o over sed, and Wumpus for fold -1. ;-)

share|improve this answer
    
This is not alphabetical order, the uppercase J should still be alphabetically sorted with the other lowercase letters. –  aks. Jan 27 at 17:27
    
Oh good point aks. I must add -f (fold) to sort to ignore case. –  joeytwiddle Jan 28 at 1:38
add comment

Ruby - 33 Chars

$><<gets.chars.sort(&:casecmp)*''
share|improve this answer
    
Where is the output code? –  Jan Dvorak Jan 22 at 12:37
    
You can spare 2 characters by using *"" instead of .join. –  manatwork Jan 22 at 13:11
    
You could use p, but that's questionable, so just use puts. Also, $< is a shortcut for ARGF –  shelvacu Jan 22 at 13:19
    
@manatwork edited... –  shiva Jan 22 at 13:45
    
You can spare 1 character by using $><< instead of puts as the separating space can be removed. –  manatwork Jan 22 at 13:45
show 1 more comment

PowerShell : 39

$([string[]][char[]](Read-Host)|sort)" #With spaces and symbols

Result

  .aaddeeeghhhJkklnnoooprtttwy

C# : 100

Console.Write(new string(input.ToCharArray().OrderBy(a=>char.ToLower(a)).ToArray()).Trim('.',' '));

Result

aaddeeeghhhJkklnnoooprtttwy
share|improve this answer
    
That's not a program as required by the question. –  Howard Jan 22 at 9:03
    
You don't need ToCharArray; String implements IEnumerable<char> –  Rik Jan 22 at 9:10
    
@howard so do scripts count as a program? –  Ralf de Kleine Jan 22 at 9:12
1  
Your symbol-excluding solutions only work for the sample input. That input was only a sample (real input can also include other symbols). –  Sander Jan 22 at 15:35
1  
@RalfdeKleine Sorry, I misspoke about sal, I don't think you can use that. But, you can get rid of the variable assignment with "$([string[]][char[]](Read-Host)|sort)". –  Kris Harper Jan 22 at 16:37
show 7 more comments

Perl6: 26 characters

Sorts output uppercase first, then lowercase, deletes symbols/whitespace

say [~] sort comb /\w/,get

If whitespace/symbols in output may be ignored too, this is only 21 characters.

say [~] get.comb.sort

This sorts case-insensitively, keeps symbols (26 chars)

say [~] get.comb.sort: &lc
share|improve this answer
    
It has to sort case-insensitively but it can ignore whitespace and symbols if preferred. –  Timtech Jan 25 at 18:24
add comment

Perl 34

Now takes input from STDIN.

print sort{lc$a cmp lc$b}<>=~/\w/g

Perl 18

If output including capitals first and symbols included is acceptable:

print sort<>=~/./g
share|improve this answer
    
I suspect you can shorten it further by taking the string from input (as per the description) instead of getting it from the cmdline. –  breadbox Jan 22 at 9:46
    
Oooh right you are! –  Dom Hastings Jan 22 at 9:56
add comment

I present a 128-char C solution without using any built-in sorting and ToLower functions:

i,j;main(k){char s[99];gets(s);for(;i<strlen(s);){j=i-1;k=s[i++];while(j>=0&&(s[j]|32)>(k|32))s[j+1]=s[j--];s[j+1]=k;}puts(s);}

More readable version:

i,j; main(k) {
    char s[99];
    gets(s);
    for(;i<strlen(s);) {
        j=i-1;
        k=s[i++];
        while( j>=0 && (s[j]|32)>(k|32) )
            s[j+1]=s[j--];
        s[j+1]=k;
    }
    puts(s);
}
share|improve this answer
add comment

APL 16

      ⍞←A[⍋48|⎕av⍳A←⍞]
Johnny walked the dog to the park.
      aaddeeeghhhJkklnnoooprtttwy.
share|improve this answer
    
This doesn't meet the requirements, because J doesn't come before a, d, e, etc. –  Timtech Jan 25 at 17:40
    
Thank you. Updated to fold case before sorting. –  Mark Plotnick Jan 25 at 18:17
    
Great job there +1 –  Timtech Jan 25 at 18:22
add comment

k (10 9)

Reads from stdin

x@<_x:0:0

Example

x@<_x:0:0
Johhny walked the dog to the park.
"      .aaddeeeghhhhJkklnoooprtttwy"
share|improve this answer
add comment

C#: 83

Console.Write(new string(Console.ReadLine().OrderBy(i=>i+"".ToLower()).ToArray()));

Update: 65

Executable in LinQPad

new string(Console.ReadLine().OrderBy(i=>i+"").ToArray()).Dump();
share|improve this answer
1  
You can remove the Dump and state it runs in LinqPad's Expression Mode :) –  Jacob Jun 30 at 14:33
add comment

Python 3: 45

print(''.join(sorted(input(),key=str.lower)))
share|improve this answer
    
I'm not into Python but does your code remove the spaces en the period? –  Ralf de Kleine Jan 22 at 8:39
    
No, but "Spaces and symbols can be ignored or deleted", so I just ignore them! –  evuez Jan 22 at 8:43
    
Ah reading is difficult ;) –  Ralf de Kleine Jan 22 at 9:12
add comment

F# (68)

I'm learning F# so I'm sure this could be shorter:

let f s=s|>Seq.sortBy(fun c->Char.ToLower(c))|>Seq.iter(printf "%c")

Output:

> f "Johnny walked the dog to the park."
        .aaddeeeghhhJkklnnoooprtttwy 
share|improve this answer
add comment

Haskell, 88

import Data.List
import Data.Char
import Data.Ord
main=interact$sortBy$comparing toLower

(38 without imports from standard lib)

share|improve this answer
add comment

J, 12 characters

(/:32|a.i.])

Ignores any non-alpha characters.

share|improve this answer
    
This task asks for a program. I can see no I/O here. If you are using any interpreter flags, you have to state them - and count them into the character count. –  Jan Dvorak Jan 22 at 12:35
    
@JanDvorak Okay, would a function count - f=., or do you want me to add the 1!:1[1? –  Gareth Jan 22 at 12:37
    
1!:1[1 and echo please –  Jan Dvorak Jan 22 at 12:38
    
@JanDvorak Why would you want echo? –  Gareth Jan 22 at 12:38
    
Does the J interpreter automatically output the result of the last expression when running a script file? Or, how do you run it? –  Jan Dvorak Jan 22 at 12:40
show 1 more comment

Javascript - 74

Unfortunately, due to the way JS sorts characters, we cannot use standard sorting function:

prompt().split("").sort(function(a,b){return a.localeCompare(b)}).join("")

Actually this can be shortened to:

prompt().split("").sort((a,b)=>a.localeCompare(b)).join("")
share|improve this answer
add comment

R, 48 characters

cat(sort(unlist(strsplit(scan(,""),""))),sep="")

Example usage:

> cat(sort(unlist(strsplit(scan(,""),""))),sep="")
1: Johnny walked the dog to the park.
8: 
Read 7 items
.aaddeeeghhhJkklnnoooprtttwy
share|improve this answer
add comment

q/k4 (3? 5? 8?)

if it's sufficient to enter the code and the input directly into the REPL, it's just asc:

q)asc"Johnny walked the dog to the park."
`s#"      .Jaaddeeeghhhkklnnoooprtttwy"

the `s# is bit of q notation that indicates that the string is in sorted order (can be binary searched, etc.). if it has to go, that costs two characters, making five:

q)`#asc"Johnny walked the dog to the park."
"      .Jaaddeeeghhhkklnnoooprtttwy"

if you want it provided on stdin, it's time to switch to k4 (and we get rid of the `s# for free), and it's an eight-character solution:

  x@<x:0:0
Johnny walked the dog to the park.
"      .Jaaddeeeghhhkklnnoooprtttwy"

that one, btw, will work as a code file exactly as is (still eight characters, since q is fine with not having the final newline in a code file). normally there would be issues with a welcome banner and with the REPL staying open, but if you pass the input as a herestring, all that goes away:

$ cat asc.k
x@<x:0:0
$ q asc.k<<<'Johnny walked the dog to the park.'
"\n      .Jaaddeeeghhhkklnnoooprtttwy"
$ 

not actually sure where that extra newline in the output is coming from....

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.