Remove Non-Alphabetic Characters from Strings in C
Getting Started: Understanding the Basics
Before diving into the program, make sure you have a solid grasp of the following C programming concepts:
- Arrays
- Strings
- For loops
- While and do…while loops
If you’re new to these topics, take a moment to review them before proceeding.
The Program: Removing Non-Alphabetic Characters
#include <stdio.h>
#include <ctype.h>
int main() {
char line[100];
char result[100] = "";
int i, j = 0;
printf("Enter a string: ");
fgets(line, sizeof(line), stdin);
for (i = 0; line[i]; i++) {
if (isalpha(line[i])) {
result[j++] = line[i];
}
}
result[j] = '\0';
printf("Output: %s\n", result);
return 0;
}
The Logic Behind the Program
The program works as follows:
- We initialize an empty string,
result
, to store the filtered characters. - The
for
loop iterates over each character in the input string, checking if it’s an alphabet using theisalpha()
function. - If the character is an alphabet, we append it to the
result
string. - Once the loop completes, we’re left with a string containing only alphabetic characters.
Sample Output
Try running the program with the input "Hello, World! 123"
and see the output:
Output: "HelloWorld"
This program demonstrates the power of C programming in removing unwanted characters from strings, leaving behind only the alphabets.