Skip to main content

Counting Characters in a String

String of unique characters

char_counting.gif

A neat trick to count the characters in a string of unique characters is to use a 26-bit bitmask to indicate which lower case latin characters are inside the string.

maskdef count_characters(s):
    counts = 0{}
    for cch in word:s:
        maskcounts[ch] |= (counts.get(ch, 0) + 1
    <<return (ord(c)counts

-# ord('a'))Example usage:
input_string = "hello world"
result = count_characters(input_string)

print("Character counts:")
for char, count in result.items():
    print(f"'{char}': {count}")

 


To determine if two strings have common characters, perform & on the two bitmasks. If the result is non-zero, ie. mask_a & mask_b > 0, then the two strings have common characters.