How to count the occurence of specific characters

2019-09-21 08:41发布

问题:

Please. .kindly help me on this problem. .

Output:

Enter string: already

A - 2

B - 0

C - 0

D - 1

E - 1

回答1:

Write a procedure that loops over the entire string in search of a specific character. For each match increment a counter. Upon return display the result as character DL occurs DH times:
e.g. "A - 2".

mov  dl, "A"
call CountChar
... print result ...
mov  dl, "B"
call CountChar
... print result ...


CountChar:
  mov  dh, 0
  mov  cx, ... length of the input string ...
  jcxz Ready
  mov  bx, ... address of the input string ...
 Again:
  cmp  [bx], dl
  jne  Skip
  inc  dh
 Skip:
  inc  bx
  loop Again
 Ready:
  ret


回答2:

Depending on the language you're supporting (read: not all languages that use 'A' to 'E' have the same number of chars), create an array of unsigned values (the data type is also depending on the longest plausible size of an array), then enumerate from the start of the given alphabet to the end, counting the discoveries and incrementing the assigned array entry.
For completeness: You didn't call out if the case counts (read: is 'a' to be counted as 'A')... if they are to be counted separately, you'll need to preserve a suitable storage for the varied cases. Once the alphabet has been enumerated, simply walk from the beginning of the array to the end, dumping the discoveries. It's not the most elegant solution... but does meet the provided parameters.