Program to Remove characters in a string except alphabets

Program to Remove characters in a string except alphabets

21 April 2023

21 April 2023

Write a Program to Remove characters in a string except alphabets



If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get a string as input from user which contains non-alphabets and then remove all the characters other than alphabets.

 

Input

Hello5678

Output

Hello

 

C Program

#include<stdio.h>

#include<string.h>

int main()

{

    char str[20];

    int j;

    printf("Enter a string: ");

    scanf("%s",str);

    for(int 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("String with alphabets alone is: ");

    printf("%s",str);

    return 0;

}

 

C++ Program

#include<iostream>

#include<string.h>

using namespace std;

int main()

{

    char str[20];

    int j;

    cout<<"Enter a string: ";

    cin>>str;

    for(int 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<<"String with alphabets alone is: ";

    cout<<str;

    return 0;

}

 

 

Java

import java.util.Scanner;

public class Main

{

              public static void main(String[] args) {

                             Scanner sc =new Scanner(System.in);

     System.out.print("Enter String : ");

     String str = sc.nextLine();

     str=str.replaceAll("[^a-zA-Z]","");

     System.out.println("String with only alphabets: "+str);

              }

}

 

Python

Str1 = input('Enter a String: ')

Str2 =''

for i in Str1:

    if (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122):

        Str2+=i

print('String with alpbhabets only: ' +Str2)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023


Related Articles

Ask Us Anything !