Contents

Three delimiters (with.Java)

   Oct 22, 2023     2 min read

In this article, we learned how to split a string with three separators.

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

Given an arbitrary string, we want to split the string using the letters “a”, “b”, and “c” as separators.

For example, if the given string is “baconlettucetomato”, the list of split strings will be [“onlettu”, “etom”, “to”].

Given a string myStr, complete the solution function to return an array that stores the strings split using “a”, “b”, and “c” in order, as shown in the example above.

However, if there are no other characters between the two separators, it will store nothing, and if the array to return is empty, it will return [“EMPTY”].

Example input and output
myStrresult
“baconlettucetomato”[“onlettu”, “etom”, “to”]
“abcd”[“d”]
“cabab”[“EMPTY”]

My solution to the problem

class Solution {
    public String[] solution(String myStr) {
        StringBuilder str = new StringBuilder("");
        boolean insideWord = false;
        for(int i = 0; i < myStr.length(); i++){
            if(myStr.charAt(i) == 'a' || myStr.charAt(i) == 'b' || myStr.charAt(i) == 'c'){
                if (insideWord) {
                    str.append(' ');
                    insideWord = false;
                }
            } else{
                str.append(myStr.charAt(i));
                insideWord = true;
            }
        }
        if(str.length() == 0){
            str.append("EMPTY");
        }
        String[] answer = str.toString().split(" ");
        return answer;
    }
}
Explanation of the solution

The main logic is to iterate over the input string myStr, checking for each character, and if it encounters the characters ‘a’, ‘b’, ‘c’, remove them and split the word.

We use the insideWord variable to keep track of whether we are inside the current word.

Use the StringBuilder object str to dynamically build the string.

The append(char c) method of StringBuilder class: adds a character to the string builder.

toString() method of class StringBuilder: Converts a StringBuilder object to a string.

split(String regex) method of class String: Splits a string by a regular expression pattern or delimiter and returns it as an array of strings.