Program to remove all characters in a string except alphabets

Program to remove all characters in a string except alphabets is discussed here. Given a string, remove all the characters except alphabets and display it as output.

For example, consider the following example

Input and Output Format:

Input consists of a string. Assume the maximum length of the string is 200. The characters in the string can contain both uppercase, lowercase, and symbols.


Sample Input:

pro$#&gra7m

Sample Output:

program

Algorithm to remove all characters in a string except alphabets

  • Input the string from the user.
  • Traverse the string, character by character.
  • If the character is not an alphabet, do not add it to the resultant string.
  • If the character is an alphabet, add it to┬áthe resultant string.
  • Print the string.

Program to remove all characters in a string except alphabets is given below.

/* C program to remove all characters in a string except alphabets */
#include<stdio.h>

int main()
{
char str[150];
int i, j;
printf(“\nEnter a string : “);
gets(str);

for(i = 0; str[i] != ‘\0’; ++i)
{
while (!( (str[i] >= ‘a’ && str[i] <= ‘z’) || (str[i] >= ‘A’ && str[i] <= ‘Z’) || str[i] == ‘\0’) )
{
for(j = i; str[j] != ‘\0’; ++j)
{
str[j] = str[j+1];
}
str[j] = ‘\0’;
}
}
printf(“\nResultant String : “);
puts(str);
return 0;
}

/* C++ program to remove all characters in a string except alphabets */
#include <bits/stdc++.h>
using namespace std;

int main()
{
char str[150];
int i, j;
cout << “\nEnter a string : “;
cin >> str;

for(i = 0; str[i] != ‘\0’; ++i)
{
while (!( (str[i] >= ‘a’ && str[i] <= ‘z’) || (str[i] >= ‘A’ && str[i] <= ‘Z’) || str[i] == ‘\0’) )
{
for(j = i; str[j] != ‘\0’; ++j)
{
str[j] = str[j+1];
}
str[j] = ‘\0’;
}
}
cout << “\nResultant String : ” << str << endl;
return 0;
}

/* Java program to remove all characters in a string except alphabets */
import java.util.*;

public class Main
{
public static void main(String args[])
{
String str;
int i, j;
Scanner sc = new Scanner(System.in);
System.out.print(“\nEnter the string : “);
str = sc.nextLine();
for (i = 0; i < str.length(); i++)
{
if (str.charAt(i) < ‘A’ || str.charAt(i) > ‘Z’ && str.charAt(i) < ‘a’ || str.charAt(i) > ‘z’)
{
str = str.substring(0, i) + str.substring(i + 1);
i–;
}
}
System.out.print(str);
}
}

# Python program to remove all characters in a string except alphabets

import re
str = input(“Enter the string : “)
result = re.sub(r'[^a-zA-Z]’, “”, str)
print(“Resultant String : “, result)

Output:

remove all characters in a string except alphabets