Print Only Alphabets In Python
Extract and print only alphabetic characters from a given string containing mixed content.
Understand the Problem
Problem Statement
A string S is passed as input. S can contain alphabets, numbers, and special characters. The program must print only the alphabetic characters present in S.
Constraints
- The length of the input string is between 1 and 1000 characters.
- The string can contain alphabets, numbers, and special characters.
- The output should contain only alphabetic characters in the order they appear in the input.
Examples
abcd_5ef8!xyzabcdefxyzThe input string contains alphabets (a,b,c,d,e,f,x,y,z) and special characters (5,8,_!). Only the alphabetic characters are printed in sequence.
1239_-87The input string contains only numbers and special characters. Since there are no alphabetic characters, nothing is printed.
Solution
#include <stdio.h>
#include <ctype.h>
int main() {
char s[1001];
fgets(s, sizeof(s), stdin);
for (int i = 0; s[i] != '\0'; i++) {
if (isalpha(s[i])) {
printf("%c", s[i]);
}
}
return 0;
}The C solution reads the input string using fgets(). It then iterates through each character of the string. For each character, it uses the isalpha() function from ctype.h to check if it's an alphabetic character. If the character is alphabetic, it is printed using printf(). The loop continues until the null terminator is reached.