Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by every other separator

Tags:

java

There's a string

String str = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";

How do I split it into strings like this "ggg;ggg;" "nnn;nnn;" "aaa;aaa;" "xxx;xxx;" ???????

like image 925
Николай Беляков Avatar asked Oct 08 '16 19:10

Николай Беляков


People also ask

How do you split with multiple separators?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

How do I split a string into multiple places?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.


2 Answers

Using Regex

    String input = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
    Pattern p = Pattern.compile("([a-z]{3});\\1;");
    Matcher m = p.matcher(input);
    while (m.find())
        // m.group(0) is the result
        System.out.println(m.group(0));

Will output

ggg;ggg;

nnn;nnn;

aaa;aaa;

xxx;xxx;

like image 85
Erik Avatar answered Nov 07 '22 17:11

Erik


I assume that the you only want to check if the last segment is similar and not every segment that has been read.

If that is not the case then you would probably have to use an ArrayList instead of a Stack.

I also assumed that each segment has the format /([a-z])\1\1/.

If that is not the case either then you should change the if statement with:

(stack.peek().substring(0,index).equals(temp))

public static Stack<String> splitString(String text, char split) {
    Stack<String> stack = new Stack<String>();
    int index = text.indexOf(split);
    while (index != -1) {
        String temp = text.substring(0, index);
        if (!stack.isEmpty()) {
            if (stack.peek().charAt(0) == temp.charAt(0)) {
                temp = stack.pop() + split + temp;
            }
        }
        stack.push(temp);
        text = text.substring(index + 1);
        index = text.indexOf(split);
    }
    return stack;
}
like image 39
nick zoum Avatar answered Nov 07 '22 15:11

nick zoum