Truncate and Sort Strings (with.Java)
In this article, we learned how to cut and sort a string.
We’ll do this by solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.
Let’s start with the problem
Problem
You are given a string myString.
Complete a solution function that truncates that string based on “x”, creates an array, and returns the array sorted alphabetically.
However, do not put the empty string in the array to be returned.
Example input and output
myString: “axbxcxdx”
result: [“a”,”b”,”c”,”d”]
My solution to the problem
import java.util.*;
class Solution {
public String[] solution(String myString) {
ArrayList<String> arr = new ArrayList<String>();
String str = "";
for(int i = 0; i < myString.length(); i++){
if(myString.charAt(i) == 'x'){
arr.add(str);
str = "";
}else{
str += myString.charAt(i);
}
}
if (!str.isEmpty()) {
arr.add(str);
}
arr.removeIf(String::isEmpty);
Collections.sort(arr);
String[] answer = new String[arr.size()];
for(int j = 0; j < answer.length; j++){
answer[j] = arr.get(j);
}
} return answer;
}
}
Solution
ArrayList
String str = “”;: Creates an empty string, str, to store the current substring.
for(int i = 0; i < myString.length(); i++) { … }: Starts a loop that traverses the given string myString character by character.
if(myString.charAt(i) == ‘x’) { … }: Checks to see if the current character is “x”. If it is “x”, add the substring str up to this point to the list arr and initialize str.
Otherwise, append the current character to str.
Traverse the string through the loop, extracting the substring based on “x” and storing it in the arr list.
if (!str.isEmpty()) { arr.add(str); }: For the final substring processing, if str is not empty, add it to the arr list.
arr.removeIf(String::isEmpty);: Remove the empty string from the arr list using the removeIf method.
Collections.sort(arr);: Sort the arr list alphabetically.
String[] answer = new String[arr.size()];: Create the result array answer based on the arr list with the length determined.
for(int j = 0; j < answer.length; j++) { … }: Copy the substring stored in the arr list to the answer array.
The function ends and returns the answer array. This array contains the substring separated by “x”, sorted alphabetically except for the empty string.