![]() |
VOOZH | about |
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 : GeeksforGeeksInput : 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:
GeeksforGeeks
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:
GeeksforGeeks
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:
GeeksforGeeks
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:
GeeksforGeeks
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.
GeeksforGeeks