Here is a pretty simple and simple example of how I will do this
String string = " \nabc \n 1 2 3 \nxyz "; //Input string = string // You can mutate this string .replaceAll("(\s|\n)", "") // This is from your code .replaceAll(".(?=.)", "$0 "); // This last step will add a space // between all letters in the // string...
You can use this example to check if the last regular expression works:
class Foo { public static void main (String[] args) { String str = "FooBar"; System.out.println(str.replaceAll(".(?=.)", "$0 ")); } }
Exit: "F oo B ar"
More about lookarounds in regex here: http://www.regular-expressions.info/lookaround.html
This approach makes it work on any line input, and this is just one more step added to your original work to accurately answer your question. Happy coding :)
source share