Remove all characters other than alphabets from string

04 May, 2022
Given a string consisting of alphabets and others characters, remove all the characters other then alphabets and print the string so formed. Examples:  
Input : $Gee*k;s..fo, r'Ge^eks?
Output : GeeksforGeeks

Input : P&ra+$BHa;;t*ku, ma$r@@s#in}gh
Output : PraBHatkumarsingh
 
To remove all the characters other than alphabets(a-z) && (A-Z), we just compare the character with the ASCII value and the character whose value does not lie in the range of alphabets, we remove those character using string erase function.  
C++
Java
Python3
C#
Javascript
// CPP program to remove all the// characters other then alphabets#include <bits/stdc++.h>using namespace std; // function to remove characters and// print new stringvoid removeSpecialCharacter(string s){    for (int i = 0; i < s.size(); i++) {                 // Finding the character whose        // ASCII value fall under this        // range        if (s[i] < 'A' || s[i] > 'Z' &&            s[i] < 'a' || s[i] > 'z')        {              // erase function to erase            // the character            s.erase(i, 1);            i--;        }    }    cout << s;} // driver codeint main(){    string s = "$Gee*k;s..fo, r'Ge^eks?";    removeSpecialCharacter(s);    return 0;}
// Java program to remove all the characters// other then alphabets class GFG{         // function to remove characters and    // print new string    static void removeSpecialCharacter(String s)    {        for (int i = 0; i < s.length(); i++)        {             // Finding the character whose            // ASCII value fall under this            // range            if (s.charAt(i) < 'A' || s.charAt(i) > 'Z' &&                    s.charAt(i) < 'a' || s.charAt(i) > 'z')            {                                 // erase function to erase                // the character                s = s.substring(0, i) + s.substring(i + 1);                i--;            }        }        System.out.print(s);    }         // Driver code    public static void main(String[] args)    {        String s = "$Gee*k;s..fo, r'Ge^eks?";        removeSpecialCharacter(s);    }} // This code is contributed by Rajput-Ji
# Python3 program to remove all the# characters other then alphabets # function to remove characters and# print new stringdef removeSpecialCharacter(s):     i = 0     while i < len(s):         # Finding the character whose        # ASCII value fall under this        # range        if (ord(s[i]) < ord('A') or            ord(s[i]) > ord('Z') and            ord(s[i]) < ord('a') or            ord(s[i]) > ord('z')):                             # erase function to erase            # the character            del s[i]            i -= 1        i += 1     print("".join(s)) # Driver Codeif __name__ == '__main__':    s = "$Gee*k;s..fo, r'Ge^eks?"    s = [i for i in s]    removeSpecialCharacter(s) # This code is contributed by Mohit Kumar
// C# program to remove all the characters// other then alphabetsusing System; class GFG {         // function to remove characters and    // print new string    static void removeSpecialCharacter(string s)    {        for (int i = 0; i < s.Length; i++)        {             // Finding the character whose            // ASCII value fall under this            // range            if (s[i] < 'A' || s[i] > 'Z' &&                    s[i] < 'a' || s[i] > 'z')            {                                 // erase function to erase                // the character                s = s.Remove(i,1);                i--;            }        }                 Console.Write(s);    }         // Driver code    public static void Main()    {        string s = "$Gee*k;s..fo, r'Ge^eks?";        removeSpecialCharacter(s);    }} // This code is contributed by Sam007.
<script>// Javascript program to remove all the characters// other then alphabets         // function to remove characters and    // print new string   function removeSpecialCharacter(s)   {       for (let i = 0; i < s.length; i++)        {               // Finding the character whose            // ASCII value fall under this            // range            if (s[i] < 'A' || s[i] > 'Z' &&                    s[i] < 'a' || s[i] > 'z')            {                                   // erase function to erase                // the character                s = s.substring(0, i) + s.substring(i + 1);                i--;            }        }        document.write(s);   }       // Driver code   let s = "$Gee*k;s..fo, r'Ge^eks?";   removeSpecialCharacter(s);           // This code is contributed by unknown2108</script>
Output:  
GeeksforGeeks
Time complexity of above code is O(n*n) as erase() may take O(n) in worst case. We can optimize the solution by keeping track of two indexes.  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
Java
Python3
C#
Javascript
// CPP program to remove all the// characters other then alphabets#include <bits/stdc++.h>using namespace std; // function to remove characters and// print new stringvoid removeSpecialCharacter(string s){    int j = 0;    for (int i = 0; i < s.size(); i++) {                 // Store only valid characters        if ((s[i] >= 'A' && s[i] <= 'Z') ||            (s[i] >='a' && s[i] <= 'z'))        {            s[j] = s[i];            j++;        }    }    cout << s.substr(0, j);} // driver codeint main(){    string s = "$Gee*k;s..fo, r'Ge^eks?";    removeSpecialCharacter(s);    return 0;}
// Java program to remove all the// characters other then alphabets class GFG { // function to remove characters and// print new string    static void removeSpecialCharacter(String str) {        char[] s = str.toCharArray();        int j = 0;        for (int i = 0; i < s.length; i++) {             // Store only valid characters            if ((s[i] >= 'A' && s[i] <= 'Z')                    || (s[i] >= 'a' && s[i] <= 'z')) {                s[j] = s[i];                j++;            }        }        System.out.println(String.valueOf(s).substring(0, j));    } // driver code    public static void main(String[] args) {        String s = "$Gee*k;s..fo, r'Ge^eks?";        removeSpecialCharacter(s);    }} // This code is contributed by 29AjayKumar
# Python program to remove all the# characters other then alphabets # Function to remove special characters# and store it in another variabledef removeSpecialCharacter(s):    t = ""    for i in s:                 # Store only valid characters        if (i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z'):            t += i    print(t) # Driver codes = "$Gee*k;s..fo, r'Ge^eks?"removeSpecialCharacter(s) # This code is contributed by code_freak
     // C# program to remove all the// characters other then alphabetsusing System;public class GFG {  // function to remove characters and// print new string    static void removeSpecialCharacter(String str) {        char[] s = str.ToCharArray();        int j = 0;        for (int i = 0; i < s.Length; i++) {              // Store only valid characters            if ((s[i] >= 'A' && s[i] <= 'Z')                    || (s[i] >= 'a' && s[i] <= 'z')) {                s[j] = s[i];                j++;            }        }        Console.WriteLine(String.Join("",s).Substring(0, j));    }  // driver code    public static void Main() {        String s = "$Gee*k;s..fo, r'Ge^eks?";        removeSpecialCharacter(s);    }} //This code is contributed by PrinciRaj1992
<script> // JavaScript program to remove all the// characters other then alphabets // function to remove characters and// print new stringfunction removeSpecialCharacter(str){    let s = str.split("");        let j = 0;        for (let i = 0; i < s.length; i++) {              // Store only valid characters            if ((s[i] >= 'A' && s[i] <= 'Z')                    || (s[i] >= 'a' && s[i] <= 'z')) {                s[j] = s[i];                j++;            }        }        document.write((s).join("").substring(0, j));} // driver codelet s = "$Gee*k;s..fo, r'Ge^eks?";removeSpecialCharacter(s);  // This code is contributed by rag2127 </script>
Output:  
GeeksforGeeks
Time Complexity : O(n)  
Remove all characters  other than alphabets in a string. | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRemove all characters  other than alphabets in a string. | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xVe9qqjbSL4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Prabhat kumar singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
PraveenSharma4
29AjayKumar
princiraj1992
Rajput-Ji
code_freak
mohit kumar 29
unknown2108
rag2127
surinderdawra388
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Convert string to char array in C++
Reverse words in a given string
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Reverse string in Python (6 different ways)
Remove duplicates from a given string