一、字符串
Scala中的字符串类型实际上是Java String,它本身没有String
Scala中,string是不可变对象,不可修改。如果修改字符串,会产生新的字符串对象
1.1 Scala字符串
创建字符串实例
scala
var greeting = 'Hello World'
var greeting:String = 'Hello World'
如果想创建一个可以修改的字符串,可以使用String Builder 类
+=
增加字符
++=
增加字符串
scala
object NewTest {
def main(args: Array[String]): Unit = {
testString()
}
def testString() {
val buf = new StringBuilder
buf ++= "hello"
buf += '_'
buf ++= "word"
println(buf.getClass.getSimpleName)
println("buf is : " + buf.toString);
}
}
shell
StringBuilder
buf is : hello_word
1.2 字符串长度length
scala
def stringLength() {
var palindrome = "hello word"
var len = palindrome.length()
println("String Length is : " + len)
}
String Length is : 10
1.3 字符串连接concat
concat
和+
都可以
scala
val stringA = "hello"
val stringB = "word"
val stringC = stringA + stringB
1.4 创建格式化字符串
String 类中可以使用 printf() 方法来格式化字符串并输出,String format() 方法可以返回 String 对象而不是 PrintStream 对象。
scala
def stringFormat(): Unit = {
val floatVar = 12.456
val intVar = 2000
val stringVar = "scala入门"
val fs = printf("浮点型变量为 %f, 整型变量为 %d, 字符串为 %s", floatVar, intVar, stringVar)
val getChar0 = stringVar.charAt(0)
val getChar1 = stringVar.charAt(1)
val getChar = stringVar.charAt(5)
println(fs)
print(getChar0, getChar1, getChar)
}
浮点型变量为 12.456000, 整型变量为 2000, 字符串为 scala入门()
入
1.5 字符串的其他用法
更多的请参考 https://www.runoob.com/scala/scala-strings.html
返回指定位置的字符 str.charAt(int index)
, index从0开始
scala
def moreUse(): Unit = {
val string1 = "helloWord"
val string2 = "learnScala"
val compare = string1.compareTo(string2) //按字典顺序比较两个字符串
val equal = string1.contentEquals(string2) //两个字符串是否相等
val endif = string1.endsWith("ls") //是否以"ls"结尾
val idx = string1.indexOf('l') // 'l'的第一个index
val idxs = string1.indexOf('l', 2) // 从位置2开始,'l'的第一个index
val stringIdx = string1.indexOf("ll") // 字符串'll'的index
val lastIdx = string2.lastIndexOf('a',6) // string2 index 0到6组成的字符穿,从倒数开始第一个'a'对应的index
println(s"compare $compare, is equal $equal, string1 is end ls $endif")
println(s"string1 index of l is $idx, index of l start from index 1 is $idxs, indexOf ll is $stringIdx")
println(s"lastIdx of string2 from index0 to 7 is $lastIdx")
}
compare -4, is equal false, string1 is end ls false
string1 index of l is 2, index of l start from index 1 is 2, indexOf ll is 2
lastIdx of string2 from index0 to 7 is 2