Concatenate characters in Scala - scala

Suppose we have a string "code". How would we concatenate any two characters? Say for example we need to concatenate last two characters,
str.init.last + str.last gives result as 201. How would we get de instead?

You can use string interpolation to make any combination of characters:
scala> val code = "code"
code: String = code
scala> s"${code(1)}${code(3)}"
res0: String = oe

"code".init.last.toString + "code".last.toString
val res7: String = de
(use toString first to convert char to String and then concatenate with +)

Related

Scala: Replace all space characters with %20

I need to replace all space characters with %20. I wrote this in Scala
strToConvert.map(c => if (Character.isSpaceChar(c)) "%20" else c).mkString
Is there any better way to do this in Scala?
[Edit]
Lets assume replaceAll is not available and we'd like to implement algorithm similar to replaceAll method
you can use String.replaceAll(what_to_replace, with_what).
eg. to replace single whitespace with %20
scala> val input = "this is my http request execute me"
input: String = this is my http request execute me
scala> input.replaceAll(" ", "%20")
res1: String = this%20is%20my%20http%20request%20%20%20%20%20%20%20%20%20%20execute%20me
or use \\s regex (matches single whitespace character)
scala> input.replaceAll("\\s", "%20")
res2: String = this%20is%20my%20http%20request%20%20%20%20%20%20%20%20%20%20execute%20me
If you want multiple whitespaces to replace to one single %20, then use \\s+ which matches sequence of one or more whitespace characters
scala> input.replaceAll("\\s+", "%20")
res3: String = this%20is%20my%20http%20request%20execute%20me

Scala Regex with $ and String Interpolation

I am writing a regex in scala
val regex = "^foo.*$".r
this is great but if I want to do
var x = "foo"
val regex = s"""^$x.*$""".r
now we have a problem because $ is ambiguous. is it possible to have string interpolation and be able to write a regex as well?
I can do something like
val x = "foo"
val regex = ("^" + x + ".*$").r
but I don't like to do a +
You can use $$ to have a literal $ in an interpolated string.
You should use the raw interpolator when enclosing a string in triple-quotes as the s interpolator will re-enable escape sequences that you might expect to be interpreted literally in triple-quotes. It doesn't make a difference in your specific case but it's good to keep in mind.
so val regex = raw"""^$x.*$$""".r
Using %s should work.
var x = "foo"
val regex = """^%s.*$""".format(x).r
In the off case you need %s to be a regex match term, just do
val regex = """^%s.*%s$""".format(x, "%s").r

How to combine raw with string interpolation in Scala?

Just started Scala and have a question.
val num = 10
val str = "Learning\t${num}Scala"
Now I am trying to print str without escaping \t but with num interpolation. Is this possible? Tried couple of variations below but they didn't work
scala>s"${str}"
scala>s"""${str}"""
scala>raw"""${str}"""
The question is how do I print Learning\t10Scala
Here is something that can be done, with same amount of code.
Write a function called times and make it insert some string in the middle of some other string
scala> def times(n: Int)(str: String): String = List.fill(n)(str).mkString("")
times: (n: Int)String
scala> s"""hello${times(3)("\t")}world"""
res0: String = hello world

Split function difference between char and string arguments

I try the following code in scala REPL:
"ASD-ASD.KZ".split('.')
res7: Array[String] = Array(ASD-ASD, KZ)
"ASD-ASD.KZ".split(".")
res8: Array[String] = Array()
Why this function calls have a different results?
There's a big difference in the function use.
The split function is overloaded, and this is the implementation from the source code of Scala:
/** For every line in this string:
Strip a leading prefix consisting of blanks or control characters
followed by | from the line.
*/
def stripMargin: String = stripMargin('|')
private def escape(ch: Char): String = "\\Q" + ch + "\\E"
#throws(classOf[java.util.regex.PatternSyntaxException])
def split(separator: Char): Array[String] = toString.split(escape(separator))
#throws(classOf[java.util.regex.PatternSyntaxException])
def split(separators: Array[Char]): Array[String] = {
val re = separators.foldLeft("[")(_+escape(_)) + "]"
toString.split(re)
}
So when you're calling split() with a char, you ask to split by that specific char:
scala> "ASD-ASD.KZ".split('.')
res0: Array[String] = Array(ASD-ASD, KZ)
And when you're calling split() with a string, it means that you want to have a regex. So for you to get the exact result using the double quotes, you need to do:
scala> "ASD-ASD.KZ".split("\\.")
res2: Array[String] = Array(ASD-ASD, KZ)
Where:
First \ escapes the following character
Second \ escapes character for the dot which is a regex expression, and we want to use it as a character
. - the character to split the string by

How do I escape tilde character in scala?

Given that i have a file that looks like this
CS~84~Jimmys Bistro~Jimmys
...
using tilde (~) as a delimiter, how can i split it?
val company = dataset.map(k=>k.split(""\~"")).map(
k => Company(k(0).trim, k(1).toInt, k(2).trim, k(3).trim)
The above don't work
Hmmm, I don't see where it needs to be escaped.
scala> val str = """CS~84~Jimmys Bistro~Jimmys"""
str: String = CS~84~Jimmys Bistro~Jimmys
scala> str.split('~')
res15: Array[String] = Array(CS, 84, Jimmys Bistro, Jimmys)
And the array elements don't need to be trimmed unless you know that errant spaces can be part of the input.