There is a problem on CodingBat called repeatSeparator.
Given two strings, word and a separator sep, return a big string made of count occurrences of the word, separated by the separator string.
repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"
I know how to solve it but my solution and most solutions I find on the internet uses a loop. Is there a way to solve this problem without a loop?
A pseudocode of my need return (word+rep)*count;
which won't work but is there a way to achieve similiar result?
I'd highly value any reply.
One liner using Java 11:
String repeatSeparator(String word, String sep, int count) {
return (word + sep).repeat(count-1) + word;
}
One liner using Java 8:
String repeatSeparator(String word, String sep, int count) {
return String.join(sep, Collections.nCopies(count, word));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With