Home > other >  How to insert spaces into binary String if binary number changes
How to insert spaces into binary String if binary number changes

Time:03-07

I want to change this binary string "100110001" into "1 00 11 000 1".

I tried finding the answer to that and had no luck finding it. I've tried to approach this problem using split() method.

CodePudding user response:

You can use split() but you need a regex that identifies the correct points to split. Afterward, you can combine the parts again with a space in between:

String input = "100110001";
String result = String. join(" ", input.split("(?<=(.))(?!\\1)"));
System.out.println(result);

Output:

1 00 11 000 1

Edit: The regex simply checks if the current character is not occurring again in the next position. If the character is not occurring back to back we want to split.

CodePudding user response:

It can be done without need to resort to regular expressions by utilizing a plain for loop and StringBuilder in a single pass through the given string, i.e. in O(n) time.

This approach is more simple but a bit more verbose than regex-based solution. The overall performance is almost the same.

The logic:

  • cut out cases when the given string contains less than two characters;
  • declare a local variable prev that will store a character at the previous position and initialize it with the first character of the given string;
  • iterate though the given string and in every case when previous and next characters don't match append an empty space to the result.

The code might look like this:

public static String insertSpaces(String source) {
    if (source.length() < 2) { // space can't be inserted
        return source;
    }

    StringBuilder result = new StringBuilder();
    char prev = source.charAt(0);
    for (int i = 0; i < source.length(); i  ) {
        char next = source.charAt(i);
        if (next != prev) {
            result.append(" ");
            prev = next;
        }
        result.append(next);
    }
    return result.toString();
}

main()

public static void main(String[] args) {
    String source = "100110001";
    System.out.println(insertSpaces(source));
}

output

1 00 11 000 1
  • Related