Convert a Sentence into its equivalent mobile numeric keypad sequence in C++
Convert Sentence into equivalent mobile numeric keypad sequence
Today in this article we will be discussing how to Convert Sentence into equivalent mobile numeric keypad sequence in C++.
Lets understand this with the help of example :-
- Input:- PREP
Output:- 7777337
Lets take example of “PREP” here to select P we need to press 7 and to select R we need to click 7 “3” times so 777 to select E we need to click 3 two times so 33 and again 7 so the output is 7777337
Algorithm
For obtaining a number, we need to press the number corresponding to that character for number of times equal to position of the character.
- For every character store the sequence which is required in order to reach that character like for R you need to Click 7 three times that is 777 for K select 55.
- Create a function printTheSequence(string arr[] , string input) that will take the sequence of array that we have created and the input string str.
- For every character subtract the ASCII value of ‘A’ and obtain the position in the array pointed ,by that character and add the sequence stored in that array to a string.
- If the character is a space then store 0 to output
- Then print the overall sequence.
C++ Code :-
#include <bits/stdc++.h> using namespace std; //Function string printTheSequence(string arr[],string input) { string output = ""; //length of the input string int len = input.length(); for (int i=0; i<len; i++) { //Check for the space if(input[i] == ' ') output = output + "0"; else { //Calculating index for each character int position = input[i]-'A'; output = output + arr[position]; } } return output; } //Driver Code int main() { //Storing the sequence in array string str[] = {"2","22","222","3","33","333","4","44","444", "5","55","555","6","66","666","7","77","777","7777", "8","88","888","9","99","999","9999"}; string input; cout<<"Enter the string :";
cin>>input;
cout<<"Sentence into its equivalent mobile numeric keypad sequence :";
cout << printTheSequence(str, input);
return 0; }
Output:-
Enter the string :PREP
Sentence into its equivalent mobile numeric keypad sequence :7777337
Enter the string :PREPINSTA
Sentence into its equivalent mobile numeric keypad sequence :777733744466777782

Login/Signup to comment