Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently repeat a character/string n times in Scala

I would like to do the following more efficiently:

def repeatChar(char:Char, n: Int) = List.fill(n)(char).mkString def repeatString(char:String, n: Int) = List.fill(n)(char).mkString  repeatChar('a',3)     // res0: String = aaa repeatString("abc",3) // res0: String = abcabcabc 
like image 884
TimY Avatar asked Jul 26 '15 12:07

TimY


People also ask

How do you repeat a string and number of times?

repeated = new String(new char[n]). replace("\0", s); Where n is the number of times you want to repeat the string and s is the string to repeat. No imports or libraries needed.

What is string * in Scala?

In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java. lang. String class.

How do you count the number of occurrences of a character in a string in Scala?

The count() method in Scala is used to count the occurrence of characters in the string. The function will return the count of a specific character in the string.


1 Answers

For strings you can just write "abc" * 3, which works via StringOps and uses a StringBuffer behind the scenes.

For characters I think your solution is pretty reasonable, although char.toString * n is arguably clearer. Do you have any reason to suspect the List.fill version isn't efficient enough for your needs? You could write your own method that would use a StringBuffer (similar to * on StringOps), but I would suggest aiming for clarity first and then worrying about efficiency only when you have concrete evidence that that's an issue in your program.

like image 88
Travis Brown Avatar answered Sep 26 '22 02:09

Travis Brown