📜  Scala-字符串(1)

📅  最后修改于: 2023-12-03 15:05:04.811000             🧑  作者: Mango

Scala-字符串

在Scala中,字符串是不可变的。这意味着一旦创建了一个字符串对象,它就不能被修改。Scala提供了许多方法来处理字符串,例如拼接、截取、格式化等等。

创建字符串

在Scala中创建字符串有以下几种方式:

直接使用双引号
val str1: String = "Hello World"
使用三个双引号

使用三个双引号创建字符串对象可以包含多行文本:

val str2: String = """Scala is an object-oriented programming language.
                      |It is widely used for developing scalable applications.""".stripMargin

其中的stripMargin方法用来去掉每行前面的空格:

val str3: String = "Scala is an object-oriented programming language.\n" +
                  "It is widely used for developing scalable applications."
                  
val str4: String = """Scala is an object-oriented programming language.
                      |It is widely used for developing scalable applications.""".stripMargin
                      
assert(str3 == str4)
使用加号拼接字符串
val str5: String = "Hello " + "World"
使用字符串插值器

Scala提供了三种字符串插值器:

  • s:字符串插值器
  • f:格式化字符串插值器
  • raw:原始字符串插值器
val name: String = "Tom"
val age: Int = 18

val str6: String = s"My name is $name, and I am $age years old."
val str7: String = f"$name%s is $age%d years old." // 格式化字符串插值器
val str8: String = raw"Hello\nWorld" // 原始字符串插值器,不会将\n转义为换行符

assert(str6 == "My name is Tom, and I am 18 years old.")
assert(str7 == "Tom is 18 years old.")
assert(str8 == "Hello\\nWorld")
字符串方法

Scala提供了许多字符串方法,这里列举一些常用的:

length

获取字符串的长度:

val str: String = "Hello World"
val len: Int = str.length

assert(len == 11)
substring

截取字符串:

val str: String = "Hello World"
val sub: String = str.substring(0, 5)

assert(sub == "Hello")
trim

去掉字符串前后的空格:

val str: String = "  Hello World  "
val trim: String = str.trim

assert(trim == "Hello World")
split

根据给定的分隔符拆分字符串:

val str: String = "apple,banana,orange"
val arr: Array[String] = str.split(",")

assert(arr sameElements Array("apple", "banana", "orange"))
contains

检查字符串是否包含指定的子串:

val str: String = "Hello World"
val result1: Boolean = str.contains("World")
val result2: Boolean = str.contains("Tom")

assert(result1 == true)
assert(result2 == false)
replace

替换字符串中的指定字符:

val str: String = "Hello World"
val newStr: String = str.replace("World", "Scala")

assert(newStr == "Hello Scala")
format

格式化字符串,将占位符替换为相应的值:

val name: String = "Tom"
val age: Int = 18

val str: String = "My name is %s, and I am %d years old.".format(name, age)

assert(str == "My name is Tom, and I am 18 years old.")
equals

比较两个字符串是否相等:

val str1: String = "Hello World"
val str2: String = "Hello World"
val str3: String = "Scala"

val result1: Boolean = str1.equals(str2)
val result2: Boolean = str1.equals(str3)

assert(result1 == true)
assert(result2 == false)
结语

Scala中,处理字符串是非常重要的一部分。通过本文,你已经掌握了如何创建、操作和格式化字符串,这将有助于你在工作中更加高效地进行开发。