Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve the "repeatSeparator" problem without a loop in Java?

Tags:

java

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.

like image 618
unobatbayar Avatar asked May 25 '20 12:05

unobatbayar


1 Answers

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));
}
like image 61
Aniket Sahrawat Avatar answered Sep 17 '22 11:09

Aniket Sahrawat