Split the string based on different criteria [Optimization Required]

manjunath ramigani :

I have one input string and If the string contains elseif, then I need to split that string to multiple lines as showed in expected output.

if ((tag eq 200)) then
    set weight 200
elseif ((tag eq 300)) then
    set weight 300
elseif ((tag eq 400)) then
    set weight 400
elseif ((tag eq 250)) then
    set weight 0
else pass endif

I've implemented below code to split as I showed above. It is giving an expected result. But the below code is not optimized one. Can someone suggest any optimization for the below piece of code.

public class Test {

    public static void main(String[] args) {
        String str = "if ((tag eq 200)) then set weight 200  elseif ((tag eq 300)) then set weight 300  elseif ((tag eq 400)) then set weight 400 elseif ((tag eq 250)) then set weight 0 else pass endif";
        System.out.println(str);

        if(str.contains("elseif")) {
            int lastIndex = str.lastIndexOf("then");
            String subString = str.substring(0, lastIndex + 4);
            splitTextByThen(subString);
            String subString1 = str.substring(lastIndex+4 , str.length());
            splitTextByElseIfOrElse(subString1);
        }
    }

    public static void splitTextByThen(String input) {
        String[] arr = input.split("then");
        for (int i = 0; i < arr.length; i++) {
            splitTextByElseIfOrElse(arr[i] + "then");
        }
    }

    public static void splitTextByElseIfOrElse(String input) {
        ArrayList<String> al = new ArrayList<>();
        if(input.contains("elseif")) {
            String[] arr = input.split("elseif");
            al.add(arr[0]);
            al.add("elseif " +arr[1]);
        }else if (input.contains("else")) {
            String[] arr = input.split("else");
            al.add(arr[0]);
            al.add("else " +arr[1]);
        }
        else {
            al.add(input);
        }

        for (String string : al) {
            System.out.println(string);
        }
    }
}
ernest_k :

Your code can look much simpler (and more readable) if you use regular expressions:

String result = str.replaceAll(" (?=elseif|else)", "\n")
                   .replaceAll("(?<=then) ", "\n    ");

This uses lookahead to match a space followed by elseif or else, replacing with \n, and lookbehind to match a space following then and replacing it with \n followed by 4 spaces.

And the output of that is:

if ((tag eq 200)) then
    set weight 200 
elseif ((tag eq 300)) then
    set weight 300 
elseif ((tag eq 400)) then
    set weight 400
elseif ((tag eq 250)) then
    set weight 0
else pass endif

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148107&siteId=1