C++ Program to Remove all Characters in a String Except Alphabets.














































C++ Program to Remove all Characters in a String Except Alphabets.



Description :
To remove all the characters other than alphabets(a-z) && (A-Z), i just compare the character with the ASCII value and the character
whose value lie in the range of alphabets are then stored in same string from index 0 upto length c
and then i print the substring which contain alphabets.

-> Input and Output are :

Input : C&PP+$SEC;R*ET; S#}
Output : CPPSECRECTS

The advantage of this code:


  • Time complexity of this code is O(n).As, there is only one for loop traversing from 0 to n-1 element.


Program :

#include <bits/stdc++.h> using namespace std; void removeAllCharacter(string s) { int i,c= 0; for (i = 0; i < s.size(); i++) { if ((s[i] >= 'A' && s[i] <= 'Z') || (s[i] >='a' && s[i] <= 'z')) { s[c] = s[i]; c++; } } cout << s.substr(0, c); } int main() { string s ; getline(cin,s); removeAllCharacter(s); return 0; }

Output :


// Thank you and happy Coding.

Comments