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.
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.
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.
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:
prev that will store a character at the previous position and initialize it with the first character of the given string;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