C Program to Remove all Characters in a String Except Alphabets
This program takes a string from user and removes all characters in that string except alphabets.
Example: Remove Characters in String Except for Alphabets
#include<stdio.h>
int main()
{
char line[150];
int i, j;
printf("Enter a string: ");
gets(line);
for(i = 0; line[i] != '\0'; ++i)
{
while (!( (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') || line[i] == '\0') )
{
for(j = i; line[j] != '\0'; ++j)
{
line[j] = line[j+1];
}
line[j] = '\0';
}
}
printf("Output String: ");
puts(line);
return 0;
}
This program takes a string from the user and stored it in the variable line.
, within the for loop, each character in the string is checked if it’s an alphabet or not.
If any character inside a string is not an alphabet, all characters after it including the null character shifted by 1 position to the left
C program to remove all characters in a string except alphabets:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100], new_str[100];
int i, j = 0;
printf("Enter a string:\n");
gets(str);
for (i = 0; i < strlen(str); i++) {
if (isalpha(str[i])) {
new_str[j] = str[i];
j++;
}
}
new_str[j] = '\0';
printf("Original string: %s\n", str);
printf("String with only alphabets: %s\n", new_str);
return 0;
}
Explanation:
#include <stdio.h>
,#include <string.h>
and#include <ctype.h>
include the standard input-output, string, and character functions header files respectively in our program.char str[100], new_str[100];
declares two character arraysstr
andnew_str
to store the original and modified strings respectively.int i, j = 0;
declares two loop variablesi
andj
.- The
printf()
the statement is used to display a message to the user to input a string and thegets()
function is used to input the string. - The
for
the loop starting fromfor (i = 0; i < strlen(str); i++)
checking each character in the stringstr
using theisalpha()
function, which returns true if the character is an alphabet. If the character is an alphabet, it is added to thenew_str
array and the index is incremented. - The statement
new_str[j] = '\0';
adds the null character at the end of the modified string to indicate the end of the string. - The last
printf()
the statement displays the original and modified strings.
When we compile and run this program, it will prompt the user to input a string and then remove all characters except alphabets. Finally, it will display both the original and modified strings.