![]() |
VOOZH | about |
Given string str of length N, the task is to remove uppercase, lowercase, special, numeric, and non-numeric characters from this string and print the string after the simultaneous modifications.
Examples:
Input: str = “GFGgfg123$%”
Output: After removing uppercase characters: gfg123$%
After removing lowercase characters: GFG123$%
After removing special characters: GFGgfg123
After removing numeric characters: GFGgfg$%
After removing non-numeric characters: 123
Input: str = “J@va12”
Output: After removing uppercase characters: @va12
After removing lowercase characters: J@12
After removing special characters: Jva12
After removing numeric characters: J@va
After removing non-numeric characters: 12
Naive Approach: The simplest approach is to iterate over the string and remove uppercase, lowercase, special, numeric, and non-numeric characters. Below are the steps:
1. Traverse the string character by character from start to end.
2. Check the ASCII value of each character for the following conditions:
Time Complexity: O(N)
Auxiliary Space: O(1)
Regular Expression Approach: The idea is to use regular expressions to solve this problem. Below are the steps:
1. Create regular expressions to remove uppercase, lowercase, special, numeric, and non-numeric characters from the string as mentioned below:
- regexToRemoveUpperCaseCharacters = “[A-Z]”
- regexToRemoveLowerCaseCharacters = “[a-z]”
- regexToRemoveSpecialCharacters = “[^A-Za-z0-9]”
- regexToRemoveNumericCharacters = “[0-9]”
- regexToRemoveNon-NumericCharacters = “[^0-9]”
2. Compile the given regular expressions to create the pattern using Pattern.compile() method.
3. Match the given string with all the above Regular Expressions using Pattern.matcher().
4. Replace every matched pattern with the target string using the Matcher.replaceAll() method.
Below is the implementation of the above approach:
After removing uppercase characters: gfg123$% After removing lowercase characters: GFG123$% After removing special characters: GFGgfg123 After removing numeric characters: GFGgfg$% After removing non-numeric characters: 123
Time Complexity: O(N)
Auxiliary Space: O(1)