Remove characters from a string except alphabets

Problem Statement: Write a program to remove all characters from a string except alphabets in a given string.

Examples:

Example 1:
Input: string str = "take12% *&u ^$#forward"
Output: takeuforward
Explanation:
Characters 1,2,%,*,&,^,$,# along with whitespaces are 
removed but the order of remaining alphabets is preserved.

Example 2:
Input: String str = "1.Python & 2.Java"
Output: PythonJava
Explanation: 
Characters 1.&2. along with whitespaces are removed 
but the order of remaining alphabets is preserved.

Solution

Disclaimer: Don’t jump directly to the solution, try it out yourself first.

Approach

  • Keep on iterating the given string
  • If there is any lowercase or uppercase alphabet then add it to the resultant string
  • Don’t include any other remaining characters (even whitespaces) into the resultant string.
  • Return the resultant string

Code:

C++ Code

#include<bits/stdc++.h>

using namespace std;
string solve(string str, int n) {
  string ans;
  for (int i = 0; i < n; i++) {
    int ascii = (int) str[i]; // ascii value

    if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) // if alphabets
      ans.push_back(str[i]);
  }
  return ans;
}
int main() {

  // Input string
  string str = "take12% *&u ^$#forward";
  int n = str.length();

  cout << "Resultant string:" << "\n";
  cout << solve(str, n) << "\n";
  return 0;
}

Output:

Resultant string:
takeuforward

Time Complexity: O(n)

Space Complexity: O(n) 

Java Code

public class tUf {
  public static String solve(String str, int n) {
    StringBuffer ans = new StringBuffer();

    for (int i = 0; i < n; i++) {
      int ascii = (int) str.charAt(i); //ascii value

      if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) // if alphabets
        ans.append(str.charAt(i));
    }

    return ans.toString();
  }
  public static void main(String args[]) {
    String str = "take12% *&u ^$#forward";
    int n = str.length();

    System.out.println("Resultant string:");
    System.out.println(solve(str, n));
  }
}

Output:

Resultant string:
takeuforward

Time Complexity: O(n)

Space Complexity: O(n) 

Special thanks to Rishiraj Girmal for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article