val s1 = "hello"
val s2 = "he"+"llo"
s1==s2
val s3 = null
s3==s2
res0:Boolean=true
res1:Boolean=false
val s4 = "Hello"
s1.toUpperCase == s4.toUpperCase
res2:Boolean=true
val foo = """this is
a topic"""
foo.replaceAll("\n"," ")
res3:String = this is a topic
"hello world".split(" ")
"hello,world".split(",")
res4:Array[String] = Array(hello,world)
res5:Array[String] = Array(hello,world)
s
f
raw
在字符串前以开头,将变量值替换变量名
val name = "fred"
println(s"$name is 20 years old")
结果输出:
fred is 20 years old
用s
作字符串插值,可以在字符串内嵌入变量,在字符串前面添加字母s
是在创建一个处理字符串字面量 ${}
内可以嵌入任何表达式
val age = 1
println(s"$name is ${age+1} years old")
结果输出:
fred is 2 years old
f
字符串插值可以格式化内部字符串
println(f"$name is $age%.1f years old")
结果输出:
fred is 1.0 years old
raw
字符串插值可以避免转义
raw"foo\nbar"
结果输出:
foo\nbar
format
方法:
val s = "%s is %d years old".format(name,age)
结果输出:
fred is 1 years old
map
filter
flatmap
for
foreach
val upper = "hello,world".map(c=>c.toUpper)
"hello,world".map(_.toUpper)
"hello,world".filter(_!='o')
结果是一样的结果输出:
HELLO,WORLD
HELLO,WORLD
hell,wrld
for(c<-"hello" if c!='l')yield c.toUpper
HEO
"hello".foreach(println)
h
e
l
l
o
在一个string上调用.r
方法可以创建一个Regex对象,之后在查找是否含有一个匹配时就可以用findFirstIn
,此方法返回option
类型,当需要查找是否完全匹配时可以用findAllIn
,此方法返回一个迭代器
val pattern = "[0-9]+".r
结果输出:
scala.util.matching.Regex = [0-9]+
找到第一个匹配:
val address = "101 main street 123"
val match1 = pattern.findFirstIn(address)
val match2 = pattern.findAllIn(address)
match2.foreach(println)
结果输出:
Option[String] = Some(101)
non-empty iterator
101
123
option
的方式有以下场景getOrElse
option
foreach
循环中使用option
replaceAll
[String].replaceAll([Regex],[Char])
replaceAllIn
[Regex].replaceAllIn([String],[Char])
replaceFirst
replaceFirstIn
String
类型是不可变的,可以在一个String
上调用replaceAll
,把结果赋给新的变量
val address = "123 main street".replaceAll("[0-9]","x")
结果输出:
xxx main street
可以创建一个正则表达式,调用replaceAllIn
方法
val regex = "[0-9]".r
val newadd = regex.relaceAllIn("123 main","q")
结果输出:
qqq main
val address = "123 main street".replaceFirst("[0-9]","x")
结果输出
x23 main street
val pattern = "([0-9]+) ([A-Za-z]+)".r
val pattern(count,fruit) = "100 bananas"
count:String = 100
fruit:String = bananas
val string = "hello"
string.charAt(1)
string(1)
string.apply(1)
结果输出:
e
e
e
Scala中执行string(1)
的时候会将代码转换成string.apply(1)
执行
定义一个隐式转换的类,在类里定义一些方法
implicit class StringImprovements(s:String){
def increment=s.map(c=>(c+1).toChar)
}
val result = "HAL".increment
IBM