Last active
May 29, 2021 18:16
-
-
Save boukadam/6fc1eca7658765732d37e5da166fc3f6 to your computer and use it in GitHub Desktop.
Java - Indent a string by curly braces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String indent(String expression) { | |
List<String> strings = Stream.of(expression) | |
.map(e -> e.replace("{", "{#")) | |
.map(e -> e.replace("}", "#}#")) | |
.flatMap(e -> Arrays.stream(e.split("[#\\n]"))) | |
.map(String::trim) | |
.filter(e -> !e.isEmpty()) | |
.collect(Collectors.toList()); | |
var indent = 0; | |
StringBuilder sb = new StringBuilder(); | |
for (String string : strings) { | |
if (string.equals("}")) { | |
indent--; | |
} | |
sb.append(" ".repeat(indent)).append(string).append("\n"); | |
if (string.indexOf('{') != -1) { | |
indent ++; | |
} | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment