Given a string of English alphabets. The task is, for every character in the string print its position in the English alphabets.
Note: The characters in the string are considered to be case-insensitive. That is, both ‘A’ and ‘a’ is at the first position.
Output: 7 5 5 11 19
‘G’ is the 7th character of the alphabets
‘e’ is the 5th and so on…
Output: 1 12 7 15 18 9 20 8 13 19
A letter’s position in Alphabet can easily be found by performing logical AND operation with the number 31.
Note that this is only applicable to letters and not special characters.
Every letter has an ASCII value which can be represented in binary form. Performing the bitwise and of this value with the number 31 will give the letter’s position in the alphabets.
Below is the implementation of the above approach:
7 5 5 11 19
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes