# Display number of occurrences for every character in an input string

The code should take a string as input from keyboard:

The definition of insanity is quoting the same phrase again and again and not expect despair.


The output should be like this(not sorted in any particular order):

  :  15
. :  1
T :  1
a :  10
c :  1
e :  8
d :  4
g :  3
f :  2
i :  10
h :  3
m :  1
o :  4
n :  10
q :  1
p :  3
s :  5
r :  2
u :  1
t :  6
y :  1
x :  1


All ASCII characters count unicode is not a requirement, spaces, quotes,etc and input should come from keyboard / not constants, attributes, output should be printed with new line after each character like in the above example, it should not be returned as string or dumped as hashmap/dictionary etc, so x : 1 and x: 1 are ok, but {'x':1,... and x:1 are not.

Q: Function or complete program taking stdin and writing stdout?
A: Code needs to be a program taking input using standard in and display the result via standard out.

# Scoreboard:

Shortest overall: 5 bytes

Shortest overall: 7 bytes

• All ascii characters as input? Or just printable? Or up to unicode? Will there be newlines? Jan 22, 2014 at 8:21
• Can I create a function, or is a whole program necessary? Can I output all the ascii characters and print 0 as the number of occurrences? Jan 22, 2014 at 8:21
• Is the output format strict, or it suffices to preserve the meaning? Jan 22, 2014 at 8:32
• Your edit did not address my question. Jan 22, 2014 at 9:00
• You didn't say if the output needs to be sorted alphabetically. You didn't say if the separator needs to be " : " (note the two spaces after the :) or if other(shorter) seperators are fine. You didn't address the unicode/encoding issue. Jan 22, 2014 at 18:11

## PHP - 68 (or 39) bytes

<?foreach(count_chars(fgets(STDIN),1)as$k=>$v)echo chr($k)." :$v
";


Output for the example text:

  : 15
. : 1
T : 1
a : 10
c : 1
d : 4
e : 8
f : 2
g : 3
h : 3
i : 10
m : 1
n : 10
o : 4
p : 3
q : 1
r : 2
s : 5
t : 6
u : 1
x : 1
y : 1


If the exact output is not required, this would work for 39 bytes:

<?print_r(count_chars(fgets(STDIN),1));


Sample output:

Array
(
[32] => 15
[46] => 1
[84] => 1
[97] => 10
[99] => 1
[100] => 4
[101] => 8
[102] => 2
[103] => 3
[104] => 3
[105] => 10
[109] => 1
[110] => 10
[111] => 4
[112] => 3
[113] => 1
[114] => 2
[115] => 5
[116] => 6
[117] => 1
[120] => 1
[121] => 1
)


where each numerical index refers the ordinal value of the character it represents.

I suspect very strongly that using an in-built function that does exactly what the problem states will soon be disallowed.

• $argv[1] instead of fgets(STDIN) saves 4 bytes. Dec 2, 2016 at 16:56 # k (8 7) #:'=0:0  Example k)#:'=:0:0 The definition of insanity is quoting the same phrase again and again and not expect despair. T| 1 h| 3 e| 8 | 15 d| 4 f| 2 i| 10 n| 10 t| 6 o| 4 s| 5 a| 10 y| 1 q| 1 u| 1 g| 3 m| 1 p| 3 r| 2 x| 1 c| 1 .| 1  edit: Down to seven, H/T Aaron Davies ## Explanation Take a String from keyboard : k)0:0 text "text"  Group the distinct elements and return a map containing key as distinct characters and values are the indices where the distinct elements occur. k)=0:0 text t| 0 3 e| ,1 x| ,2  Now count values of each entry in the map. k)#:'=0:0 text t| 2 e| 1 x| 1  • Pretty incredible. Jan 22, 2014 at 23:39 • the : in =: is superfluous; k)#:'=0:0 works fine (7 chars). (bonus for knowing about 0:0, i had no idea!) Jan 23, 2014 at 4:59 • A detailed explanation would be really cool :) Jan 24, 2014 at 20:12 • q translation is easier to understand - count each group read0 0 Jan 25, 2014 at 16:15 # GNU core utils - 2922 20 chars (53 with formatting) Wumpus's improvement (20 chars): fold -1|sort|uniq -c  Firefly's improvement (22 chars): grep -o .|sort|uniq -c  joeytwiddle's original (29 chars): sed 's+.+\0\n+g'|sort|uniq -c  Originally I used sed to simply add a newline after each character. Firefly improved on that with grep -o ., since -o displays every matched pattern on its own line. Wumpus pointed out a further improvement using fold -1 instead. Nice work! uniq does the real work, although it only applies to sorted lists. Note that the output format does not exactly match the example in the question. That requires a final run through sed to swap the arguments. (Waiting on an answer to Jan Dvorak's question to see if this is required...) Reformatting with sed is "only" another 33 characters! (Total 53) |sed 's/ *$$.*$$ $$.$$/\2 : \1/'  Awk can almost do the job whilst adding only 25 chars, but it hides the first space. Silly awk! |awk '{print$2" :  "$1}'  I wonder if improvements can be made in the reformatting stage... • For sed you can use & for "whole match" instead of \0, though grep -o . is slightly shorter yet. It's worth mentioning that the output of uniq -c differs slightly from the one given in the question. Jan 22, 2014 at 8:59 • Oh thanks you! Updated. I should not forget grep -o; it is a useful one. Jan 22, 2014 at 9:08 • fold -1 does the same thing as grep -o . – user15244 Jan 22, 2014 at 15:28 • Awesome :) Learning new tricks! Jan 22, 2014 at 15:38 • ptx -S. does the same trick. Jan 22, 2014 at 23:36 # Ruby 1.9.3: 53 characters (Based on @shiva's and @daneiro's comments.) gets.split("").uniq.map{|x|puts x+" : #{$_.count x}"}


Sample run:

bash-4.1$ruby -e 'a=gets;a.split("").uniq.map{|x|puts"#{x} : #{a.count x}"}' <<< 'Hello world' H : 1 e : 1 l : 3 o : 2 : 1 w : 1 r : 1 d : 1 : 1  ## Ruby: 44 characters Not respecting the output format: s=Hash.new 0;gets.chars{|c|s[c]+=1};pp s  Sample run: bash-4.1$ ruby -rpp -e 's=Hash.new 0;gets.chars{|c|s[c]+=1};pp s' <<< 'Hello, world!'
{"H"=>1,
"e"=>1,
"l"=>3,
"o"=>2,
","=>1,
" "=>1,
"w"=>1,
"r"=>1,
"d"=>1,
"!"=>1,
"\n"=>1}

• 63 chars a=gets.strip;a.split('').uniq.each{|x|puts"#{x} : #{a.count(x)}"}
– Siva
Jan 22, 2014 at 12:22
• Why to strip()? The question says, “all characters count”. Jan 22, 2014 at 12:35
• Well, gets will return \n even if you dont intend to
– Siva
Jan 22, 2014 at 12:37
• Nope. Only returns \n if it was really passed. Passing it is a side-effect of using here-string. pastebin.com/gCrgk9m1 Jan 22, 2014 at 12:42
• Using $_ and ditching a is still sound though. And c+"... instead of "#{c}... Jan 22, 2014 at 14:57 # Python 3: 76 characters ## 76 import collections as c for x,y in c.Counter(input()).items():print(x,':',y)  ### 44 (print same characters many times, see Wasi's answer for a valid version) a=input() for x in a:print(x,':',a.count(x))  • The 45 char version prints characters more than once. Jan 22, 2014 at 14:40 • Right... Thanks for noticing! Jan 22, 2014 at 14:43 • @evuez I just fixed your 45 char version. But, you removed it so I have submitted it once again. Have a look – Wasi Jan 22, 2014 at 15:21 ## Perl 6: 21 chars .say for get.comb.Bag  (REPL) > .say for get.comb.Bag The definition of insanity is quoting the same phrase again and again and not expect despair. "T" => 1 "h" => 3 "e" => 8 " " => 15 "d" => 4 "f" => 2 "i" => 10 "n" => 10 "t" => 6 "o" => 4 "s" => 5 "a" => 10 "y" => 1 "q" => 1 "u" => 1 "g" => 3 "m" => 1 "p" => 3 "r" => 2 "x" => 1 "c" => 1 "." => 1 ## APL (15) M,⍪+⌿Z∘.=M←∪Z←⍞  If you really need the :, it's 19 (but there's others who aren't including it): M,':',⍪+⌿Z∘.=M←∪Z←⍞  Output:  M,⍪+⌿Z∘.=M←∪Z←⍞ The definition of insanity is quoting the same phrase again and again and not expect despair. T 1 h 3 e 8 16 d 4 f 2 i 10 n 10 t 6 o 4 s 5 a 10 y 1 q 1 u 1 g 3 m 1 p 3 r 2 x 1 c 1 . 1  • Semi-serious question -- what's it like maintaining legacy APL code? Jan 25, 2014 at 2:41 • @MichaelStern: No idea, I've never had to do that. But I'd guess it's no worse than maintaining other legacy code. APL is actually quite easy to read once you're used to it. Jan 25, 2014 at 21:44 ### R, 30 characters table(strsplit(readline(),""))  Example usage: > table(strsplit(readline(),"")) The definition of insanity is quoting the same phrase again and again and not expect despair. . a c d e f g h i m n o p q r s t T u x y 15 1 10 1 4 8 2 3 3 10 1 10 4 3 1 2 5 6 1 1 1 1  • Good idea! But the question says the code must print the result. Your code just returns the result. I suppose you need cat. Jan 24, 2014 at 16:22 • @SvenHohenstein well it wasn't specified when i answered (i answered before revision 4 of the question)... but as a matter of fact cat will only return the values not the value names (i. e. the characters). So it would need a more complex solution. Jan 24, 2014 at 16:35 ## Perl 5, 54 characters map{$h{$_}++}split//,<>;print"$_ : $h{$_}\n"for keys%h

• Very nice solution, easy to read. That would need to be sort keys%h, though. Jan 22, 2014 at 11:49
• Hey @protist, looks good! I agree with @primo though! You can however save two chars using $_=<>;s/./$h{$_}++/eg; or map{$h{$_}++}<>=~/./g; instead of map{$h{$_}++}split//,<>; Jan 22, 2014 at 15:24 • @DomHastings or $h{_}++for<>=~/./g, which I think might be optimal. Literal newline instead of \n as well. Jan 22, 2014 at 15:33 • Ah nice, even better! Yes, I forgot to mention the literal newline, that's become my new favourite -1 byte! Jan 22, 2014 at 15:52 # JavaScript 1. 66 53 bytes: prompt(a={}).replace(/./g,function(c){a[c]=-~a[c]}),a  2. 69 56 bytes: b=prompt(a={});for(i=b.length;i--;){a[b[i]]=-~a[b[i]]};a  3. 78 65 bytes: prompt().split('').reduce(function(a,b){return a[b]=-~a[b],a},{})  N.B.: In all cases deleted number of bytes refer to extra console.log() call which is pointless if run in the console. Big thanks to @imma for the great catch with -~a[b] and prompt(a={}). This definitely saved some more bytes. • map instead of a loop help a little also (a[b[i]]||0)+1 can be reduced to -~a[b[i]] & console.log can probably go, just returning the last value, giving prompt(a={}).split("").map(function(c){a[c]=-~a[c]});a – imma Jan 22, 2014 at 12:47 • you can change for into for in - testing in empty tab produces the same results. Also, the last ; is not needed, thus: b=prompt(a={});for(i in b){a[b[i]]=-~a[b[i]]}a Jan 22, 2014 at 13:35 • nice :-) stick the b=... into the for & swop the for{}'s for a ; for another 2 bytes off : for(i in b=prompt(a={}))a[b[i]]=-~a[b[i]];a – imma Jan 22, 2014 at 16:04 • although they may want exact text output :-/ which puts it/me back up by 36 (to 79) bytes : for(i in b=prompt(a={}))a[b[i]]=-~a[b[i]];for(n in a)console.log(n+" : "+a[n]) – imma Jan 22, 2014 at 16:25 • @VisioN only if the primitives are overloaded - for in indeed gives you functions in SO, but not in empty tab ;) Jan 22, 2014 at 18:09 # Python 2, correctly (58) s=raw_input() for l in set(s):print l+" : "+str(s.count(l))  Output: python count.py The definition of insanity is quoting the same phrase again and again and not expect despair. : 15 . : 1 T : 1 a : 10 c : 1 e : 8 d : 4 g : 3 f : 2 i : 10 h : 3 m : 1 o : 4 n : 10 q : 1 p : 3 s : 5 r : 2 u : 1 t : 6 y : 1 x : 1  # Python 2, cheetah style (41) s=input() print {l:s.count(l) for l in s}  Output: python count.py "The definition of insanity is quoting the same phrase again and again and not expect despair." {' ': 15, '.': 1, 'T': 1, 'a': 10, 'c': 1, 'e': 8, 'd': 4, 'g': 3, 'f': 2, 'i': 10, 'h': 3, 'm': 1, 'o': 4, 'n': 10, 'q': 1, 'p': 3, 's': 5, 'r': 2, 'u': 1, 't': 6, 'y': 1, 'x': 1}  • Forgot to remove the brackets after print in the second one, that makes it 41 Jan 23, 2014 at 8:30 • You can go down to 52 chars with your first version: for l in set(s):print l,":",s.count(l). For the second one, removing unnecessary spaces makes you win 2 chars: print{l:s.count(l)for l in s} Jan 23, 2014 at 13:48 ## Mathematica, 61 bytes Map[{#[[1]], Length@#} &, Gather@Characters[Input[]]] // TableForm  It then pops up this dialog box, and for the sample sentence, produces as output ## python 3, 49 Stealing idea from evuez t=input() for i in set(t):print(i,':',t.count(i))  input: The definition of insanity is quoting the same phrase again and again and not expect despair.  output:  : 15 . : 1 T : 1 a : 10 c : 1 e : 8 d : 4 g : 3 f : 2 i : 10 h : 3 m : 1 o : 4 n : 10 q : 1 p : 3 s : 5 r : 2 u : 1 t : 6 y : 1 x : 1  • nice improvement! why don't you remove the sorted()? Jan 22, 2014 at 15:21 • right! anyway, if you don't use a list comprehension, it's 1 char less: for i in sorted(set(t)):print(i,':',t.count(i)) Jan 22, 2014 at 15:38 • @evuez Thanks, I was supposed to add it as a comment in your code. If you like you can add it again in your solution(I will happily delete this one) :D – Wasi Jan 22, 2014 at 15:50 • Wouldn't be fair, I hadn't thought about set()! ;) Jan 22, 2014 at 16:09 # JavaScript (69 68 characters): Expects s to hold the string. _={};for(x in s)_[a=s[x]]=-~_[a];for(x in _)console.log(x+': '+_[x])  This follows the new rules perfectly. Note: This presumes a clean environment, with no custom properties on any standard object prototypes. Edit: 1 character less! ## Console output: T: 1 h: 3 e: 8 : 15 d: 4 f: 2 i: 10 n: 10 t: 6 o: 4 s: 5 a: 10 y: 1 q: 1 u: 1 g: 3 m: 1 p: 3 r: 2 x: 1 c: 1 .: 1  # Old answer (44 characters): r={};[].map.call(s,function(e){r[e]=-~r[e]})  This was valid before the rules changed. r contains the output. # APL (Dyalog Unicode), 5 bytesSBCS Full program body. Prompts for a string from STDIN and prints newline separated table to STDOUT. Leftmost column is the input characters, and counts are right-aligned with the largest number separated from its character by a single space. ,∘≢⌸⍞  Try it online! ⍞ prompt for text input from STDIN ⌸ create a keys' table consisting of , the unique element followed ∘ by ≢ the tally of the indices of its occurrence (i.e how many times it occurs) • Looks like the : is unfortunately required in the output (you can't delete this answer). Mar 29, 2018 at 19:49 • @EriktheOutgolfer How do you deduce that? Clearly OP found this answer acceptable, in accordance with an old comment. – Adám Mar 29, 2018 at 20:42 • Another reason for spec to be in the question itself... Mar 29, 2018 at 20:48 # Haskell, 93 import Data.List main=getLine>>=mapM(\s->putStrLn[head s]++" : "++show(length s)).group.sort


PowerShell (49)

[char[]](read-host)|group|%{$_.Name+":"+$_.Count}


# C# (178 220 chars)

Based on @Spongeman's comment I changed it up a bit:

using C=System.Console;using System.Linq;class P{static void Main()
.OrderBy(x=>x.Key).Select(g=>g.Key+":"+g.Count())));}}


Line breaks added for readability, my first feeble attempt at code golf! :)

class P {static void Main(){var d=new Dictionary<char,int>();
.Join("\n",d.Keys.Select(x=>x+":" +d[x])));}}

• doesn't compile. this one does: 178 chars. using System.Linq;using C=System.Console;class F{static void Main(){C.WriteLine(string.Join("\n",C.ReadLine().GroupBy(c=>c).Select(g=>g.Key+" : "+g.Count()).OrderBy(s=>s)));}} Jan 23, 2014 at 19:15
• 168: using C=System.Console;using System.Linq;class F{static void Main(){foreach(var g in C.ReadLine().GroupBy(c=>c).OrderBy(g=>g.Key))C.WriteLine(g.Key+" : "+g.Count());}} Jan 23, 2014 at 19:21
• apparently sorting is unneccesary, 150: using C=System.Console;using System.Linq;class F{static void Main(){foreach(var g in C.ReadLine().GroupBy(c=>c))C.WriteLine(g.Key+" : "+g.Count());}} Jan 24, 2014 at 5:57
• Wow. Quick or coincidence ? You replied just a second after I updated my answer :D Just noticed that sorting wasn't explicitly mentioned! Jan 24, 2014 at 5:58
• 148: namespace System{using Linq;class F{static void Main(){foreach(var g in Console.ReadLine().GroupBy(c=>c))Console.WriteLine(g.Key+" : "+g.Count());}} Jan 24, 2014 at 20:02

# Sclipting, 19 characters

梴要⓶銻꾠⓷❸虛變梴❶⓺減負겠⓸⓸終丟


## Output

T:1
h:3
e:8
:15
d:4
f:2
i:10
n:10
t:6
o:4
s:5
a:10
y:1
q:1
u:1
g:3
m:1
p:3
r:2
x:1
c:1
.:1


If you want the spaces around the :, change 꾠 to 긃똠, making it 20 characters.

## Explanation

Get length of input string.

Stack is now [ input, length ]
While {

Get first character of string and push ":"
⓶銻꾠
Stack is now [ length, input, firstchar, ":" ]
Replace all occurrences of that character with empty string
⓷❸虛變
Stack is now [ length, firstchar, ":", reducedinput ]
Get the length of that, calculate difference to previous length, push "\n"
梴❶⓺減負겠
Stack is now [ firstchar, ":", reducedinput, newlength, diff, "\n" ]
Move the input string and length back up, leaving output below it
⓸⓸
Stack is now [ firstchar, ":", diff, "\n", reducedinput, newlength ]
------------------------'                -------'
Every iteration of the               The length provides
While loop generates                 the While loop's
a bit like this                      terminating condition
} End While

Discard the length which is now 0



# F# (66 59 49, 72 with prescribed formattting)

let f s=s|>Seq.countBy(id)|>Seq.iter(printfn"%A")


Output:

> f The definition of insanity is quoting the same phrase again and again and not expect despair.
(' ', 15)
('.', 1)
('T', 1)
('a', 10)
('c', 1)
('d', 4)
('e', 8)
('f', 2)
('g', 3)
('h', 3)
('i', 10)
('m', 1)
('n', 10)
('o', 4)
('p', 3)
('q', 1)
('r', 2)
('s', 5)
('t', 6)
('u', 1)
('x', 1)
('y', 1)


With the prescribed formatting, it becomes:

let f s=s|>Seq.countBy(id)|>Seq.iter(fun(a,b)->printfn"\"%c\" :  %d"a b)

• You can drop a character by switching away from the piped syntax for a few of the function calls: let f s=Seq.countBy id (Seq.sort s)|>Seq.iter(printfn"%A") Jan 25, 2014 at 1:02
• In fact, why even sort in the first place? let f s=Seq.countBy id s|>Seq.iter(printfn"%A") Jan 25, 2014 at 1:10

# Mathematica, 34 29 bytes

Not sure why the other Mathematica answer is so complicated... ;)

Grid@Tally@Characters@Input[]


# Bash (20 15 characters)

 ptx -S.|uniq -c
10                                        a
1                                        c
4                                        d
8                                        e
2                                        f
3                                        g
3                                        h
10                                        i
1                                        m
10                                        n
4                                        o
3                                        p
1                                        q
2                                        r
5                                        s
6                                        t
1                                        T
1                                        u
1                                        x
1                                        y


ASCII encoding now supported

# Bash (23 characters):

xxd -p -c1|sort|uniq -c

1 0a
15 20
1 2e
1 54
10 61
1 63
4 64
8 65
2 66
3 67
3 68
10 69
1 6d
10 6e
4 6f
3 70
1 71
2 72
5 73
6 74
1 75
1 78
1 79


ASCII formatting not supported

• just out of curiosity, do you really need |sort| here, AFAIK ptx will already produce a sorted list of chars which you can feed directly to "uniq -c" Dec 2, 2016 at 15:13
• @zeppelin a little googling confimrs what you've said Dec 2, 2016 at 15:35

# Java 8, 273253249246239 200 bytes

interface I{static void main(String[]a){int m[]=new int[999],i=0;for(int c:new java.util.Scanner(System.in).nextLine().getBytes())m[c]++;for(;++i<999;)if(m[i]>0)System.out.printf("%c: %d%n",i,m[i]);}}


-24 bytes thanks to @Poke.
-7 bytes thanks to @OlivierGrégoire.

Explanation:

Try it here.

interface I{                        // Class
static void main(String[]a){      //  Mandatory main-method
int m[]=new int[999],           //  Integer-array to count the occurrences
i=0;                        //  Index-integer, starting at 0
for(int c:new java.util.Scanner(System.in).nextLine().getBytes())
//   Loop over the input as bytes:
m[c]++;                       //    Increase the occurrence-counter of the char by 1
for(;++i<999;)                  //   Loop over the array:
if(m[i]>0)                    //    If the current character occurred at least once:
System.out.print("%c: %d%n",//     Print with proper formatting:
i,                         //      The character
m[i]);}}                   //      and the occurrence-count

• 249 bytes import java.util.*;class I{public static void main(String[]a){Map m=new HashMap();for(char c:new Scanner(System.in).nextLine().toCharArray()){m.put(c,m.get(c)!=null?(int)m.get(c)+1:1);}for(Object e:m.keySet()){System.out.println(e+": "+m.get(e));}}}
– Poke
Dec 2, 2016 at 14:54
• m.compute(c,(k,v)->v!=null?(int)v+1:1); instead of m.put(c,m.get(c‌​)!=null?(int)m.get(c‌​)+1:1); to save 3 bytes. Mar 2, 2018 at 8:40

## Powershell, 63

$a=@{};[char[]](read-host)|%{$a[$_]++};$a.Keys|%{"$_ :"+$a[$_]}  • Each key in a hash can be accessed as a property on that hash, so you can shave off two characters by replacing each instance of $a[$_] with $a.\$_ . See help about_hash_tables Jan 24, 2014 at 21:41

## Windows Command Script - 72 Bytes

set/p.=
:a
set/a\%.:~,1%=\%.:~,1%+1
set.=%.:~1%
%.%goto:b
goto:a
:b
set\


Outputs:

\=15 (space)
\.=1
\a=10
\c=1
\d=4
\e=8
\f=2
\g=3
\h=3
\i=10
\m=1
\n=10
\o=4
\p=3
\q=1
\r=2
\s=5
\T=7
\u=1
\x=1
\y=1

• Nice! It does fold case though, but it's always amazing to see actual cleverness in batch file programming. Jan 24, 2014 at 16:40

## J, 23 chars

(~.;"0+/@|:@=)/:~1!:1]1


Slightly different output format (line 2 is stdin):

   (~.;"0+/@|:@=)/:~1!:1]1
Mississippi
┌─┬─┐
│M│1│
├─┼─┤
│i│4│
├─┼─┤
│p│2│
├─┼─┤
│s│4│
└─┴─┘


# J, 22 characters

(~.;"0+/@(=/~.))1!:1]1


Example:

   (~.;"0+/@(=/~.))1!:1]1
The definition of insanity is quoting the same phrase again and again and not expect despair.
+-+--+
|T|1 |
+-+--+
|h|3 |
+-+--+
|e|8 |
+-+--+
| |15|
+-+--+
|d|4 |
+-+--+
|f|2 |
+-+--+
|i|10|
+-+--+
|n|10|
+-+--+
|t|6 |
+-+--+
|o|4 |
+-+--+
|s|5 |
+-+--+
|a|10|
+-+--+
|y|1 |
+-+--+
|q|1 |
+-+--+
|u|1 |
+-+--+
|g|3 |
+-+--+
|m|1 |
+-+--+
|p|3 |
+-+--+
|r|2 |
+-+--+
|x|1 |
+-+--+
|c|1 |
+-+--+
|.|1 |
+-+--+


C#

string str = Console.ReadLine(); // Get Input From User Here
char chr;
for (int i = 0; i < 256; i++)
{
chr = (char)i; // Use The Integer Index As ASCII Char Value --> Convert To Char
if (str.IndexOf(chr) != -1) // If The Current Char Exists In The Input String
{
Console.WriteLine(chr + " : " + str.Count(x => x == chr)); // Count And Display
}
}
Console.ReadLine(); // Hold The Program Open.


In Our Case, If The Input Will Be "The definition of insanity is quoting the same phrase again and again and not expect despair."

The Output Will Be:

  : 15
. : 1
T : 1
a : 10
c : 1
d : 4
e : 8
f : 2
g : 3
h : 3
i : 10
m : 1
n : 10
o : 4
p : 3
q : 1
r : 2
s : 5
t : 6
u : 1
x : 1
y : 1

• The question asks for input from the keyboard, so the first line should be string str = Console.ReadLine();. But this is code-golf so it should actually be var str=Console.ReadLine();. The other comments I would like to make have to be put on hold until OP improves the question. Jan 22, 2014 at 12:15
• You're right, I edited my answer.
– Aviv
Jan 22, 2014 at 13:13

## C#: 129

This is Avivs answer but shorter:

var s=Console.ReadLine();for(int i=0;i<256;i++){var ch=(char)i;Console.Write(s.Contains(ch)?ch+":"+s.Count(c=>c==ch)+"\r\n":"");}


This is mine:

## C#: 103

foreach(var g in Console.ReadLine().OrderBy(o=>o).GroupBy(c=>c))Console.WriteLine(g.Key+":"+g.Count());

• Won't compile, need to add about 50 chars for usings/namespace/class/method definitions. Jan 22, 2014 at 19:45
• Oh, didn't know that was mandatory, I'm sorry. Jan 22, 2014 at 20:12

# Python 2 (90 chars)

import collections as c;print"\n".join("%s %s"%i for i in c.Counter(raw_input()).items())


Output when run on its own source:

  8
" 4
% 3
) 4
( 4
. 3
; 1
C 1
\ 1
_ 1
a 2
c 4
e 3
f 1
i 9
j 1
m 2
l 2
o 6
n 7
p 3
s 5
r 5
u 2
t 6
w 1