String

A string is a sequence of characters. In scala objects of strings are immutable which means a constant and cannot be changed once created.

Creating String

Creating Strings
var greetings="Hello World"  or var greetings: String ="Hello World"

Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”. String keyword can also be given in alternate declaration as shown above.
object Demo{
def main(args: Array[String])
{
var str="Hello World"
println(str)
}
}
Comparing two strings
object test{
def main(args: Array[String])
{
val s1 = "Hello"
val s2 = "Hello"
val s3 = "H" + "ello"
val s4 = null
println("Print the comprasion result for S1 and S3")
var res= s1==s3
println (res)
println("Print the comprasion result for S1 and S4")
var res1 = s1==s4
println (res1)
}
}
Concatenating strings
object test{
def main(args: Array[String])
{
val s1 = "Hello"
val s2 = "World"
println("Print the comprasion result for S1 and S4")
println (s1 + s2)
}
}
String Interpolation
object test{
def main(args: Array[String])
{
val s1 = "Hello"
val s4 = "World"
println(s"Print value $s1 and $s4 ")
}
}
Compare two strings in a case sensitive manner.
object test{
def main(args: Array[String])
{
val s1 = "Hello"
val s4 = "World"
println(s"Print value $s1 and $s4 ")
}
}
Multi-line strings.
scala> val foo = """This is
      a multiline
      String"""

foo: String =
This is
a multiline
String

scala> val speech = """Four score and
     | |seven years ago""".stripMargin
speech: String =
Four score and
seven years ago

scala> val speech = """Four score and
     | #seven years ago""".stripMargin('#')
speech: String =
Four score and
seven years ago

scala> val speech = """Four score and
     | seven years ago
     | our fathers""".stripMargin.replaceAll("\n", " ")
speech: String = Four score and seven years ago our fathers

Split the strings.
object test{
def main(args: Array[String])
{
val s1 = "hello world"
val s2 = "eggs, milk, butter, Coco Puffs"
val r1=s1.split(" ")
val r2=s2.split(",")
for(i <- r1)
{
println(i)
}
for(i <- r2)
{
println(i)
}
val s = "eggs, milk, butter, Coco Puffs"
val r3=s1.split(" ").map(_.trim)
r3.foreach(println)
}
}
Replace String
object Demo
{
def main(args:Array[String])
{
val result = "Nidhi".replace('N', 'n')
println(result)
}
}
Replace String with Empty String
object Demo
{
def main(args:Array[String])
{
val name="Jeeta"
val afterReplace=name.replace(""+'a',"")
println(afterReplace)
}
}



object Demo {
def main(args: Array[String]) {
val myString = "i can ride at a speed of 190 KmpH"
println("The string is '" + myString + "'")
println("Replacing all digits of the string with '*'")
val updatedString = myString.replaceAll("[0-9]+", "*")
println("Updated string is' " + updatedString + "'")
}
}
Index of String
object Demo
{
def main(args:Array[String])
{
val result = "Nidhi Singh".indexOf("dh")
println(result)
}
}
mkString method with Separator
The mkString() method is utilized to display all the elements of the list in a string along with a separator. 
object Demo
{
def main(args:Array[String])
{
val m1 = List(2, 3, 5, 7, 8)
val result = m1.mkString("*")
println(result)
}
}

object Demo
{
def main(args:Array[String])
{
val m1 = List(2, 3, 5, 7, 8)
val result = m1.mkString("_")
println(result)
}
}

Split strin based on regular expression
scala> "hello world, this is Al".split("\\s+")
res9: Array[String] = Array(hello, world,, this, is, Al)

split with char
scala> "hello world".split(' ')
res11: Array[String] = Array(hello, world)

Expression can embedded  in {}.
scala> println(s"Age next year: ${age + 1}")
Age next year: 34

scala> println(s"You are 33 years old: ${age == 33}")
You are 33 years old: true

Create regular expression by invoking the .r method.

scala> val numPattern = "[0-9]+".r
numPattern: scala.util.matching.Regex = [0-9]+

scala> val address = "123 Main Street Suite 101"
address: String = 123 Main Street Suite 101

scala> val match1 = numPattern.findFirstIn(address)
match1: Option[String] = Some(123)

Looking for more matches.
scala> val matches = numPattern.findAllIn(address)
matches: scala.util.matching.Regex.MatchIterator = non-empty iterator

scala> matches.foreach(println)
123
101
scala> val matches = numPattern.findAllIn(address).toArray
matches: Array[String] = Array(123, 101)

val address = "123 Main Street".replaceAll("[0-9]", "x")
val regex = "[0-9]".r
 val result = "123".replaceFirst("[0-9]", "x")

Replace all substrings of the specified string value that match regexp with rep.
import org.apache.spark.sql.functions.regexp_replace
val df = spark.createDataFrame(Seq( (1, "1,3435"),(2, "1,6566"),(3, "-0,34435"))).toDF("Id", "x4")
The syntax is regexp_replace(str, pattern, replacement), which translates to:
df.withColumn("x4New", regexp_replace(df("x4"), "\\,", ".")).show

+---+--------+--------+
| Id|      x4|   x4New|
+---+--------+--------+
|  1|  1,3435|  1.3435|
|  2|  1,6566|  1.6566|
|  3|-0,34435|-0.34435|
+---+--------+--------+


scala> val a = "Marisa"
a: String = Marisa

scala> val b = "marisa"
b: String = marisa

scala> a.equalsIgnoreCase(b)
res4: Boolean = true

No comments:

Post a Comment