Remove all characters other than alphabets from string
Last Updated :
31 Jul, 2023
Given a string consisting of alphabets and others characters, remove all the characters other than 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 for the character whose value does not lie in the range of alphabets, we remove those characters using string erase function.
Implementation:
C++
// CPP program to remove all the
// characters other than alphabets
#include <bits/stdc++.h>
using namespace std;
// function to remove characters and
// print new string
void 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 code
int main()
{
string s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
return 0;
}
Java
// Java program to remove all the characters
// other than 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
# Python3 program to remove all the
# characters other than alphabets
# function to remove characters and
# print new string
def 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 Code
if __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#
// C# program to remove all the characters
// other than alphabets
using 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.
JavaScript
<script>
// Javascript program to remove all the characters
// other than 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>
Time complexity: O(N2) as erase() may take O(n) in the worst case. We can optimize the solution by keeping track of two indexes.
Auxiliary Space: O(1)
Implementation:
C++
// CPP program to remove all the
// characters other than alphabets
#include <bits/stdc++.h>
using namespace std;
// function to remove characters and
// print new string
void 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 code
int main()
{
string s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
return 0;
}
Java
// Java program to remove all the
// characters other than 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
Python3
# Python program to remove all the
# characters other than alphabets
# Function to remove special characters
# and store it in another variable
def 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 code
s = "$Gee*k;s..fo, r'Ge^eks?"
removeSpecialCharacter(s)
# This code is contributed by code_freak
C#
// C# program to remove all the
// characters other than alphabets
using 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
JavaScript
<script>
// JavaScript program to remove all the
// characters other than alphabets
// function to remove characters and
// print new string
function 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 code
let s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
// This code is contributed by rag2127
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach : Using isalpha() method:
Iterate over the characters of the string and if the character is an alphabet then add the character to the new string. Finally, the new string contains only the alphabets of the given string.
Implementation:
C++
// CPP program to remove all the
// characters other than alphabets
#include <bits/stdc++.h>
using namespace std;
// function to remove characters and
// print new string
void removeSpecialCharacter(string s)
{
// Initialize an empty string
string ans = "";
for (auto ch : s) {
// if the current character
// is an alphabet
if (isalpha(ch))
ans += ch;
}
cout << ans;
}
// driver code
int main()
{
string s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
return 0;
}
// this code is contributed by Rajdeep Mallick(rajdeep999)
Java
public class Main {
// function to remove characters and print new string
static void removeSpecialCharacter(String s) {
// Initialize an empty string
String ans = "";
for (char ch : s.toCharArray()) {
// if the current character is an alphabet
if (Character.isLetter(ch))
ans += ch;
}
System.out.println(ans);
}
// driver code
public static void main(String[] args) {
String s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
}
}
Python3
# Python program to remove all the
# characters other than alphabets
# Function to remove special characters
# and store it in another variable
def removeSpecialCharacter(s):
t = ""
for i in s:
if(i.isalpha()):
t+=i
print(t)
s = "$Gee*k;s..fo, r'Ge^eks?"
removeSpecialCharacter(s)
C#
using System;
public class Program {
public static void Main()
{
string s = "$Gee*k;s..fo, r'Ge^eks?";
RemoveSpecialCharacter(s);
}
// function to remove characters and print new string
public static void RemoveSpecialCharacter(string s)
{
// Initialize an empty string
string ans = "";
foreach(char ch in s)
{
// if the current character is an alphabet
if (Char.IsLetter(ch))
ans += ch;
}
Console.WriteLine(ans);
}
}
// This code is contributed by sarojmcy2e
JavaScript
// function to remove characters and print new string
function removeSpecialCharacter(s) {
// Initialize an empty string
let ans = "";
for (let i = 0; i < s.length; i++) {
// if the current character is an alphabet
if (/[a-zA-Z]/.test(s[i])) {
ans += s[i];
}
}
console.log(ans);
}
// driver code
let s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
// This code is contributed by princekumaras
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach: Without built-in methods.
Initialize an empty string, string with lowercase alphabets(la) and uppercase alphabets(ua). Iterate a for loop on string, if the character is in la or ua using in and not in operators concatenate them to an empty string. Display the string after the end of the loop.
Implementation:
C++
// C++ program to remove all the
// characters other than alphabets
#include<bits/stdc++.h>
using namespace std;
string removeSpecialCharacter(string s) {
string t = "";
string la = "abcdefghijklmnopqrstuvwxyz";
string ua = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < s.length(); i++) {
if(la.find(s[i]) != string::npos ||
ua.find(s[i]) != string::npos)
{
t += s[i];
}
}
cout << t << endl;
return t;
}
int main() {
string s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
return 0;
}
// This code is contributed by shivamsharma215
Java
// Java program to remove all the
// characters other than alphabets
import java.util.*;
class Gfg {
static String removeSpecialCharacter(String s)
{
// empty string to store the result
String t = "";
String la = "abcdefghijklmnopqrstuvwxyz";
String ua = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < s.length(); i++) {
// if it is a letter, add it to the result string
if (la.contains(String.valueOf(s.charAt(i)))
|| ua.contains(
String.valueOf(s.charAt(i)))) {
t += s.charAt(i);
}
}
System.out.println(t);
return t;
}
// Driver Code
public static void main(String[] args)
{
String s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
}
}
Python3
# Python program to remove all the
# characters other than alphabets
# Function to remove special characters
# and store it in another variable
def removeSpecialCharacter(s):
t = ""
la="abcdefghijklmnopqrstuvwxyz"
ua="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in s:
if(i in la or i in ua):
t+=i
print(t)
s = "$Gee*k;s..fo, r'Ge^eks?"
removeSpecialCharacter(s)
C#
// C# program to remove all the
// characters other than alphabets
using System;
class Gfg{
static string removeSpecialCharacter(string s)
{
string t = "";
string la = "abcdefghijklmnopqrstuvwxyz";
string ua = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < s.Length; i++)
if(la.Contains(s[i]) || ua.Contains(s[i]))
t += s[i];
Console.WriteLine(t);
return t;
}
public static void Main()
{
string s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
}
}
JavaScript
// JS program to remove all the
// characters other than alphabets
function removeSpecialCharacter( s) {
let t = "";
let la = "abcdefghijklmnopqrstuvwxyz";
let ua = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (let i = 0; i < s.length; i++)
{
if(la.includes(s[i]) || ua.includes(s[i]))
{
t += s[i];
}
}
console.log(t);
return t;
}
let s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
// this code is contributed by poojaagarwal2.
Time complexity: O(n), where n is the length of the input string s. This is because in the worst case, the loop in the removeSpecialCharacter function will have to iterate through all the characters in the string.
Auxiliary Space: O(n), where n is the length of the final string without special characters. This is because the function creates a new string t to store only the alphabetic characters. The size of the string t will be at most equal to the size of the original string s.
Approach: Using ord() function.The ASCII value of the lowercase alphabet is from 97 to 122. And, the ASCII value of the uppercase alphabet is from 65 to 90.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to remove special characters
// and store it in another variable
void removeSpecialCharacter(string s)
{
string t = "";
for (int i = 0; i < s.length(); i++) {
if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {
t += s[i];
}
}
cout << t << endl;
}
int main()
{
string s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
return 0;
}
Java
import java.util.*;
class GFG {
// Function to remove special characters
// and store it in another variable
static void removeSpecialCharacter(String s) {
String t = "";
for (int i = 0; i < s.length(); i++) {
if ((s.charAt(i) >= 'a' && s.charAt(i) <= 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')) {
t += s.charAt(i);
}
}
System.out.println(t);
}
public static void main(String[] args) {
String s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
}
}
Python3
# Python program to remove all the
# characters other than alphabets
# Function to remove special characters
# and store it in another variable
def removeSpecialCharacter(s):
t = ""
for i in s:
if(ord(i) in range(97,123) or ord(i) in range(65,91)):
t+=i
print(t)
s = "$Gee*k;s..fo, r'Ge^eks?"
removeSpecialCharacter(s)
C#
using System;
class GFG {
// Function to remove special characters
// and store it in another variable
static void RemoveSpecialCharacter(string s)
{
string t = "";
for (int i = 0; i < s.Length; i++) {
// Check if the character is an alphabet
// (lowercase or uppercase)
if ((s[i] >= 'a' && s[i] <= 'z')
|| (s[i] >= 'A' && s[i] <= 'Z')) {
t += s[i];
}
}
Console.WriteLine(t);
}
static void Main(string[] args)
{
string s = "$Gee*k;s..fo, r'Ge^eks?";
RemoveSpecialCharacter(s);
}
}
JavaScript
// JavaScript program to remove all the
// characters other than alphabets
// Function to remove special characters
// and store it in another variable
function removeSpecialCharacter(s)
{
let t = ""
for (let i=0; i<s.length; i++)
if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z'))
t+=s[i];
console.log(t);
}
let s = "$Gee*k;s..fo, r'Ge^eks?";
removeSpecialCharacter(s);
Similar Reads
Remove character in a String except Alphabet - Python
Sometimes, we may need to remove characters from a string except for alphabets. For example, given a string s, the task is to remove all characters except for the alphabetic ones (a-z, A-Z). Another example is if the input string is "Hello123!@#" ,the output should be "Hello". Let's explore differen
3 min read
Remove characters from a String that appears exactly K times
Given a string of lowercase letters str of length N, the task is to reduce it by removing the characters which appear exactly K times in the string. Examples: Input: str = "geeksforgeeks", K = 2 Output: eeforee Input: str = "geeksforgeeks", K = 4 Output: gksforgks Approach: Create a hash table of si
5 min read
Remove a character from a string to make it a palindrome
Given a string, we need to check whether it is possible to make this string a palindrome after removing exactly one character from this. Examples: Input : str = âabcbaâ Output : Yes we can remove character âcâ to make string palindrome Input : str = âabcbeaâ Output : Yes we can remove character âeâ
10 min read
Program for removing i-th character from a string
Given a string S along with an integer i. Then your task is to remove ith character from S. Examples: Input: S = Hello World!, i = 7Output: Hello orld!Explanation: The Xth character is W and after removing it S becomes Hello orld! Input: S = GFG, i = 1Output: GGExplanation: It can be verified that a
5 min read
Remove characters from string that appears strictly less than K times
Given a string of lowercase letters and a number K. The task is to reduce it by removing the characters which appear strictly less than K times in the string. Examples: Input : str = "geeksforgeeks", K = 2 Output : geeksgeeks Input : str = "geeksforgeeks", K = 3 Output : eeee Approach : Create a has
9 min read
Remove all occurrences of a character from a string using STL
Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string. Examples: Input:vS = "GFG IS FUN", C = 'F' Output:GG IS UN Explanation: Removing all occurrences of the character 'F' modifies S to "GG IS UN". Therefore, the required output is GG
2 min read
Minimize cost to empty a given string by removing characters alphabetically
Given string str, the task is to minimize the total cost to remove all the characters from the string in alphabetical order. The cost of removing any character at i th index from the string will be i. The indexing is 1-based. Examples: Input: str = "abcab" Output: 8 Explanation: First char âaâ at in
7 min read
Remove odd indexed characters from a given string
Given string str of size N, the task is to remove the characters present at odd indices (0-based indexing) of a given string. Examples : Input: str = âabcdefâOutput: aceExplanation:The characters 'b', 'd' and 'f' are present at odd indices, i.e. 1, 3 and 5 respectively. Therefore, they are removed f
4 min read
Remove duplicates from a string
Given a string s which may contain lowercase and uppercase characters. The task is to remove all duplicate characters from the string and find the resultant string. Note: The order of remaining characters in the output should be the same as in the original string.Example:Input: s = geeksforgeeksOutp
10 min read
Remove even frequency characters from the string
Given a string 'str', the task is to remove all the characters from the string that have even frequencies. Examples: Input: str = "aabbbddeeecc" Output: bbbeee The characters a, d, c have even frequencies So, they are removed from the string. Input: str = "zzzxxweeerr" Output: zzzweee Approach: Crea
8 min read