C Program To Convert Letters Into A Phone Number
In this article, you will learn how to write C programs that convert alphabetic letters into their corresponding digits, mimicking the layout of traditional phone keypads. This process is useful for various applications where textual input needs to be translated into a numeric format.
Problem Statement
The challenge lies in translating a given string of letters (and potentially other characters) into a phone number format, where each letter maps to a specific digit as found on a standard 12-button phone keypad. For example, 'A', 'B', 'C' map to '2'; 'D', 'E', 'F' map to '3', and so on. Non-alphabetic characters like hyphens or digits should remain unchanged.
Example
Let's consider the input string "HELLO-WORLD". The expected output, after conversion to a phone number, would be "43556-96753".
Background & Knowledge Prerequisites
To effectively understand this article, readers should have a basic understanding of:
- C Programming Basics: Variables, data types, input/output operations.
- Character Manipulation: Concepts of characters, ASCII values, and functions like
toupper()ortolower(). - Conditional Statements:
if-else ifandswitchstatements for decision making. - Loops:
fororwhileloops for iterating through strings. - Strings in C: How characters arrays are used to represent strings.
Use Cases or Case Studies
Converting letters into phone numbers has several practical applications:
- Vanity Phone Numbers: Allowing users to input memorable words (e.g., "CALL-NOW") and convert them to the corresponding phone number (2255-6669).
- Data Normalization: Standardizing phone number inputs where users might accidentally type letters instead of digits.
- Spelling Out Numbers: In systems where numeric input is cumbersome, letters can be used to represent digits.
- Educational Tools: Demonstrating character processing and mapping logic in C programming.
- Basic Text Processing: As a component in larger text processing or data conversion utilities.
Solution Approaches
We will explore two common approaches to solve this problem: using a series of if-else if statements and using a switch statement.
Approach 1: Using if-else if Statements
This approach uses a sequence of if-else if conditions to check the character and convert it to its corresponding digit.
One-line summary: Iterate through the input string, checking each character against ranges of letters using if-else if to assign the correct digit.
// Letter to Phone Number Converter (if-else if)
#include <stdio.h>
#include <string.h> // For strlen()
#include <ctype.h> // For toupper()
void convertLettersToPhoneNumber(char *str) {
for (int i = 0; str[i] != '\\0'; i++) {
char ch = toupper(str[i]); // Convert to uppercase to handle both cases
if (ch >= 'A' && ch <= 'C') {
str[i] = '2';
} else if (ch >= 'D' && ch <= 'F') {
str[i] = '3';
} else if (ch >= 'G' && ch <= 'I') {
str[i] = '4';
} else if (ch >= 'J' && ch <= 'L') {
str[i] = '5';
} else if (ch >= 'M' && ch <= 'O') {
str[i] = '6';
} else if (ch >= 'P' && ch <= 'S') { // P, Q, R, S
str[i] = '7';
} else if (ch >= 'T' && ch <= 'V') {
str[i] = '8';
} else if (ch >= 'W' && ch <= 'Z') { // W, X, Y, Z
str[i] = '9';
}
// If it's a digit or another character, it remains unchanged
}
}
int main() {
// Step 1: Declare character arrays for input and output.
char phoneNumber1[50] = "1-800-COLLECT";
char phoneNumber2[50] = "HELLO-WORLD";
char phoneNumber3[50] = "MyNumberIs123";
// Step 2: Print original strings.
printf("Original: %s\\n", phoneNumber1);
printf("Original: %s\\n", phoneNumber2);
printf("Original: %s\\n", phoneNumber3);
// Step 3: Convert letters to phone number digits.
convertLettersToPhoneNumber(phoneNumber1);
convertLettersToPhoneNumber(phoneNumber2);
convertLettersToPhoneNumber(phoneNumber3);
// Step 4: Print converted strings.
printf("Converted: %s\\n\\n", phoneNumber1);
printf("Converted: %s\\n\\n", phoneNumber2);
printf("Converted: %s\\n\\n", phoneNumber3);
return 0;
}
Sample output:
Original: 1-800-COLLECT
Original: HELLO-WORLD
Original: MyNumberIs123
Converted: 1-800-2655328
Converted: 43556-96753
Converted: 6968623747123
Stepwise explanation:
- Include Headers:
stdio.hfor input/output,string.hforstrlen(though not explicitly used in thismainfunction for loop,ctype.hfortoupper). convertLettersToPhoneNumberFunction: This function takes a character array (string) as input.- Loop Through String: A
forloop iterates over each character of the string until the null terminator (\0) is encountered. - Convert to Uppercase:
toupper(str[i])converts the current character to its uppercase equivalent. This simplifies the comparison logic, as we only need to check for uppercase letter ranges. - Conditional Checks: A series of
if-else ifstatements checks which range the uppercase character falls into (e.g., 'A' through 'C'). - Replace Character: If a match is found, the character in the original string
str[i]is replaced with its corresponding digit character (e.g., '2', '3'). - Handle Non-Letters: If the character is not a letter within the defined ranges (e.g., a digit, hyphen, space), it remains unchanged as no
ifcondition will be met to alter it. mainFunction: Demonstrates the usage with a few example strings.
Approach 2: Using a switch Statement
This approach uses a switch statement, often considered cleaner for multiple specific value checks, although character ranges are less direct.
One-line summary: Use a switch statement on each character (after converting to uppercase) to map it to its corresponding phone digit using case groups.
// Letter to Phone Number Converter (switch)
#include <stdio.h>
#include <string.h> // For strlen()
#include <ctype.h> // For toupper()
void convertLettersToPhoneNumberSwitch(char *str) {
for (int i = 0; str[i] != '\\0'; i++) {
char ch = toupper(str[i]); // Convert to uppercase for consistent checking
switch (ch) {
case 'A': case 'B': case 'C':
str[i] = '2';
break;
case 'D': case 'E': case 'F':
str[i] = '3';
break;
case 'G': case 'H': case 'I':
str[i] = '4';
break;
case 'J': case 'K': case 'L':
str[i] = '5';
break;
case 'M': case 'N': case 'O':
str[i] = '6';
break;
case 'P': case 'Q': case 'R': case 'S':
str[i] = '7';
break;
case 'T': case 'U': case 'V':
str[i] = '8';
break;
case 'W': case 'X': case 'Y': case 'Z':
str[i] = '9';
break;
default:
// Non-alphabetic characters (digits, hyphens, etc.)
// are left unchanged by default
break;
}
}
}
int main() {
// Step 1: Declare character arrays for input.
char phoneNumber1[50] = "1-800-C-A-L-L-N-O-W";
char phoneNumber2[50] = "Programming-isfun";
// Step 2: Print original strings.
printf("Original: %s\\n", phoneNumber1);
printf("Original: %s\\n", phoneNumber2);
// Step 3: Convert letters to phone number digits using the switch approach.
convertLettersToPhoneNumberSwitch(phoneNumber1);
convertLettersToPhoneNumberSwitch(phoneNumber2);
// Step 4: Print converted strings.
printf("Converted: %s\\n\\n", phoneNumber1);
printf("Converted: %s\\n\\n", phoneNumber2);
return 0;
}
Sample output:
Original: 1-800-C-A-L-L-N-O-W
Original: Programming-isfun
Converted: 1-800-2-2-5-5-6-6-9
Converted: 77647266464-47386
Stepwise explanation:
- Include Headers: Same as the previous approach.
convertLettersToPhoneNumberSwitchFunction: Similar structure to theif-else ifversion.- Loop and Convert to Uppercase: Iterates through the string and converts each character to uppercase.
switchStatement: Theswitchstatement evaluates the uppercase characterch.- Grouped
caseLabels: Multiplecaselabels (e.g.,case 'A': case 'B': case 'C':) are grouped together. Ifchmatches any of these, the code block immediately following (before the nextbreak;) is executed. - Replace Character: Inside the
caseblock,str[i]is updated to its corresponding digit character. breakStatement: Eachcaseblock ends withbreak;to exit theswitchstatement and prevent "fall-through" to subsequentcaseblocks.defaultCase: Thedefaultcase handles any characters that do not match the alphabeticcaselabels (digits, symbols, spaces), leaving them unchanged.mainFunction: Provides examples to test thisswitch-based conversion.
Conclusion
Converting letters into phone number digits is a straightforward yet practical task in C programming. Both the if-else if and switch statement approaches effectively solve this problem by mapping character ranges or specific characters to their numeric equivalents. The choice between them often comes down to personal preference or specific readability requirements for the codebase, with switch being potentially cleaner for discrete values and if-else if for ranges.
Summary
- Problem: Translate alphabetic letters in a string to corresponding phone keypad digits (e.g., A,B,C -> 2).
- Tools: Basic C programming, character functions (
toupper), loops (for), and conditional statements (if-else iforswitch). - Approach 1 (if-else if): Uses sequential
if-else ifconditions to check character ranges and replace them with digits. - Approach 2 (switch): Employs a
switchstatement with groupedcaselabels to map individual letters to digits. - Flexibility: Both methods handle uppercase/lowercase letters and preserve non-alphabetic characters.
- Applications: Useful for vanity numbers, data normalization, and general text processing.