在Scala中我们可以把字符串当成一个字符集合来使用,可以利用集合的一些特性和操作方法来处理字符串中的字符。
常用的字符串集合处理函数包括foreach,map和loop,根据不同的情况选择不同的函数。
使用map方法能够对原有字符串中每个字符做出处理然后返回处理后的字符组成的字符串。
scala> val upper = "hello world".map(_.toUpper)
upper: String = HELLO WORLD
使用foreach方法打印字符串中每一个字符,foreach方法只是处理字符没有返回值。
scala> "hello world".foreach(println)
h
e
l
l
o
w
o
r
l
d
使用for循环既可以实现map功能,也可以实现foreach功能,但是代码要比直接使用map和foreach复杂一些。
scala> for (c <- "hello world") println(c)
h
e
l
l
o
w
o
r
l
d
scala> for (c <- "hello world";if(c != 'l')) yield c.toUpper
res32: String = HEO WORD