Remove all Characters in a String Except Alphabet
Program to remove all characters in a string except alphabet is discussed here. A string is obtained as input from the user and all the characters other than the alphabets are removed from the string and the output string containing only the alphabets is displayed.
For example,
Input string: asdfg1326%^$hjk
Output string: asdfghjk
Program to remove all characters in a string except alphabet
C
// C program to remove all Characters in a String Except Alphabet
#include
int main()
{
char input[150];
int i, j;
printf(“Enter a string : “);
gets(input);
for(i = 0; input[i] != ‘\0’; ++i)
{
while (!( (input[i] >= ‘a’ && input[i] <= ‘z’) || (input[i] >= ‘A’ && input[i] <= ‘Z’) || input[i] == ‘\0’) )
{
for(j = i; input[j] != ‘\0’; ++j)
{
input[j] = input[j+1];
}
input[j] = ‘\0’;
}
}
printf(“\nOutput string : “);
puts(input);
printf(“\n”);
return 0;
}
C++
// C++ program to remove all Characters in a String Except Alphabet
#include
using namespace std;
int main()
{
string input;
int i, j;
cout << “\nEnter a string : ” << input;
> input;for(i = 0; input[i] != ‘\0’; ++i)
{
while (!( (input[i] >= ‘a’ && input[i] <= ‘z’) || (input[i] >= ‘A’ && input[i] <= ‘Z’) || input[i] == ‘\0’) )
{
for(j = i; input[j] != ‘\0’; ++j)
{
input[j] = input[j+1];
}
input[j] = ‘\0’;
}
}
cout << “\nOutput string : “;
cout << input;
return 0;
}
JAVA
// Java program to remove all characters in a string except alphabet
import java.util.*;
public class Main
{
public static void main(String[] args)
{
String input;
int i;
System.out.print(“Enter a string : “);
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
System.out.println();
//Replacing characters other than alphabets by “”
System.out.println(“Output String : ” + input.replaceAll(“[^a-zA-Z]”,””));
}
}
PYTHON 3
# Python program to remove all characters in a string except alphabet
input_str = “face i45s th678e inde56x o456$%f min567d”
newString = ”
# only the alphabets are defined as valid characters
valid = “abcdefghijklmnopqrstuvwxyz”
for char in input_str:
if char in valid:
newString += char # characters other than valid are not ignored
print (newString)
Output
Input- Enter a string:hel1456lo56wor%^ld Output- helloworld
Write a public review