In Ruby we can do this:
$ irb
>> ("aa".."bb").map { |x| x }
=> ["aa", "ab", "ac", "ad", "ae", "af", "ag", "ah", "ai", "aj", "ak", "al", "am", "an", "ao", "ap", "aq", "ar", "as", "at", "au", "av", "aw", "ax", "ay", "az", "ba", "bb"]
In Scala if I try the same I get error:
$ scala
Welcome to Scala version 2.9.1 (OpenJDK 64-Bit Server VM, Java 1.7.0_51).
scala> ("aa" to "bb").map(x => x)
<console>:8: error: value to is not a member of java.lang.String
("aa" to "bb").map(x => x)
^
How do get a range of Strings in Scala ?
Get length of the string So, a length() method is the accessor method in Scala, which is used to find the length of the given string. Or in other words, length() method returns the number of characters that are present in the string object. Syntax: var len1 = str1.
In scala, string is a combination of characters or we can say it is a sequence of characters. It is index based data structure and use linear approach to store data into memory. String is immutable in scala like java.
On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.
For this example you could do (scala 2.10)
val atoz = 'a' to 'z'
for {c1 <- atoz if c1 <= 'b'; c2 <- atoz if (c1 == 'a' || (c1 == 'b' && c2 < 'c'))} yield s"$c1$c2"
Edited as per comment, thanks (but getting a bit ugly!)
('a' to 'z').map("a" + _) :+ "ba" :+ "bb"
:)
A for comprehension would do nicely:
val abc = 'a' to 'z'
for (c1 <- abc; c2 <- abc) yield (s"$c1$c2")
This yields a Seq/Vector[String] with all the permutations you'd expect
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