Count the number of identical characters in a string. Count uppercase letters as lowercase letters. Example: input string bbBCcaA *, output *: 1 a: 2 B: 3 c: 2
Asp.net
| The Code is as follows: |
Copy code |
# Include <iostream> Using namespace std; Const int MAX_NUMBER = 200; // Count the number of identical characters Void Calc (const char * str, int len ); Int main () { Char pch [MAX_NUMBER];
// Input string Cin. getline (pch, MAX_NUMBER ); Int length = strlen (pch ); Calc (pch, length ); Return 0; } Void Calc (const char * str, int len) { Int LetterCounts [256]; // This array is the key. It stores the number of Spanish characters. Int I; For (I = 0; I <256; I ++) LetterCounts [I] = 0;
For (I = 0; I <len; I ++) { If (str [I]> = 'A' & str [I] <= 'Z ') LetterCounts [str [I] + 32] ++; // lowercase Else LetterCounts [str [I] ++; }
For (I = 0; I <256; I ++) { If (LetterCounts [I]> 0) Cout <(char) I <":" <LetterCounts [I] <endl; }
} |
Php
| The Code is as follows: |
Copy code |
<? Php // This method is purely a back-function and is not explained; Function countStr ($ str ){ $ Str_array = str_split ($ str ); $ Str_array = array_count_values ($ str_array ); Arsort ($ str_array ); Return $ str_array; } // The following is an example; $ Str = "asdfgfdas323344 ##$ fdsdfg * $ ** $ 443563536254fas "; Print_r (countStr ($ str )); ?> <? Php // This method has some data structure ideas, but it is quite understandable :) Function countStr2 ($ str ){ $ Str_array = str_split ($ str ); $ Result_array = array (); Foreach ($ str_array as $ value) {// determines whether the character is a new type. If yes, It is set to 1. If not, it is automatically added; If (! $ Result_array [$ value]) { $ Result_array [$ value] = 1; } Else { $ Result_array [$ value] ++; } } Arsort ($ result_array ); Return $ result_array; } // The following is an example; $ Str = "asdfgfdas323344 ##$ fdsdfg * $ ** $ 443563536254fas "; Var_dump (countStr2 ($ str )) ?> <? Php // This method is purely a poor version of solution 1. First, find the total classes of all characters, and then use the substr_count function one by one. Function countStr3 ($ str ){ $ Str_array = str_split ($ str ); $ Unique = array_unique ($ str_array ); Foreach ($ unique as $ v ){ $ Result_array [$ v] = substr_count ($ str, $ v ); } Arsort ($ result_array ); Return $ result_array; } // The following is an example; $ Str = "asdfgfdas323344 ##$ fdsdfg * $ ** $ 443563536254fas "; Var_dump (countStr3 ($ str )); ?> |