Method 3: Modern Elegance with ES6 and Beyond
Step 1: Extract Only the Alphabets
In this method, we're tapping into the powerful arsenal of ES6 methods, specifically map and filter, to craft a more streamlined solution.
Creating an Alphabetic Array
First off, we extract only the alphabetical characters from the string and store them in a new array, which we'll call alphaOnly.
Here's how you can do it in multiple languages:
1List<Character> alphaOnly = str.chars()
2 .mapToObj(c -> (char) c)
3 .filter(c -> Character.toString(c).matches("[a-zA-Z]"))
4 .collect(Collectors.toList());Step 2: The Transformation Act
After creating our alphaOnly array, the next phase is where the real magic happens. We'll split the original string into an array and perform a transformation using map.
Returning Non-Alphabetic Characters
During this transformation, if a character does not match our Regular Expression criteria (i.e., it's not an alphabetical character), we simply return it in its current position, leaving it untouched.
Picture this as walking through a garden and only flipping the stones that have a specific marking, while leaving all others in their original state.
xxxxxxxxxxString[] alphaOnly = str.split("").stream().filter(c -> c.matches("[a-z]")).toArray(String[]::new);return Arrays.stream(str.split("")).map( c -> { if (!c.matches("[a-z]")) { return c; }}).toArray(String[]::new);