# C PROGRAMS
String in C
➤ Read Display String in C
➤ 2D Array of Strings in C
➤ Find Length of String
➤ Copy Two Strings in C
➤ Concatenate Two Strings
➤ Compare two strings
➤ Reverse a String in C
➤ Palindrome string in C
➤ Uppercase to Lowercase
➤ Lowercase to Uppercase
➤ Remove all characters in String except alphabet
➤ Find Frequency of Characters
➤ Count Number of Words
➤ Count lines, words, & characters
➤ Count Vowel, Consonant, Digit, Space, Special Character
➤ String Pattern in C
➤ Copy Input to Output
Here we will write a C program to remove all characters in a string except the alphabet. If the string was “[email protected]” then the result in the string will be “KnowProgram”.
C Program to Remove all Characters in a String except Alphabet using another String
#include<stdio.h>
int main()
{
char s1[100],s2[100];
int i, j;
printf("Enter string: ");
fgets(s1, sizeof(s1), stdin);
for(i=0,j=0;s1[i]!='\0';i++)
{
if((s1[i]>='A' && s1[i]<='Z')||(s1[i]>='a' && s1[i]<='z'))
{
s2[j]=s1[i];
j++;
}
}
s2[j]='\0';
printf("Displaying string: %s",s2);
return 0;
}
Output for the different test-cases:-
Enter string: #[email protected]
Displaying string: KnowProgram
Enter string: [email protected] Welcome, To The Programming World!
Displaying string: HelloWelcomeToTheProgrammingWorld
This is the easiest way. In this program, we checked every character of the string. Only the character whose ASCII value is in between (including) ‘a’ to ‘z’ or ‘A’ to ‘Z’ those characters are an alphabet. Our problem was to remove all the characters except alphabet from the string. So, we checked every character of the string, if the character is an alphabet then copy it to second string. By this way finally, we get a string which has the only alphabet.
Without using Another String
#include<stdio.h>
int main()
{
char s[150];
int i, j;
printf("Enter a string: ");
fgets(s, sizeof(s), stdin);
for(i = 0; s[i] != '\0'; ++i)
{
while (!( (s[i] >= 'a' && s[i] <= 'z') ||
(s[i] >= 'A' && s[i] <='Z') ||
s[i] == '\0' ) )
{
for(j = i; s[j] != '\0'; ++j)
{
s[j] = s[j+1];
}
s[j] = '\0';
}
}
printf("Output String: %s",s);
return 0;
}
Output:-
Enter a string: ComputerA4002020Corner
Output String: ComputerACorner
In this program, we will do the same thing without using another string. If any character in the string is not an alphabet then the next character is replaced.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!
More C programming Examples on String
- Remove all characters in a string except alphabet
- Find frequency of characters in string
- C program to count the number of words in a string
- Count lines, words, and characters in a given text
- Vowel, consonant, digit, space, special character Count
- String pattern programs in C programming language
- Copy Input to Output Using C programming