Find letter's position in Alphabet using Bit operation in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string str consisting of english alphabets. Our task is to find the letter's position in the Alphabet using the Bit operation. 

Problem Description: Here, we will return the position of each character of the string as it is in english alphabets.

The characters of the string are case-insensitive i.e. “t” and “T” are treated the same.

Let’s take an example to understand the problem, 

Input: str = “Tutorialspoint”

Output: 20 21 20 15 18 9 1 12 19 16 15 9 14 20 

Solution Approach

A simple solution to find a character's position is by finding its logical AND operation with 31.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

void findLetterPosition(string str, int n) {
   
   for (int i = 0; i < n; i++) {
      cout<<(str[i] & 31) << " ";
   }
}

int main() {
   
   string str = "TutorialsPoint";
   int n = str.length();
   cout<<"The letters position in string "<<str<<" is \n";
   findLetterPosition(str, n);

   return 0;
}

Output

The letters position in string TutorialsPoint is
20 21 20 15 18 9 1 12 19 16 15 9 14 20
raja
Published on 25-Jan-2021 05:06:14
Advertisements