Scala学习之字符串篇(五):逐字符处理字符串

在Scala中咱们能够把字符串当成一个字符集合来使用,能够利用集合的一些特性和操做方法来处理字符串中的字符。函数

经常使用的字符串集合处理函数包括foreachmaploop,根据不一样的状况选择不一样的函数。oop

使用map方法可以对原有字符串中每一个字符作出处理而后返回处理后的字符组成的字符串。scala

scala> val upper = "hello world".map(_.toUpper)
upper: String = HELLO WORLD

使用foreach方法打印字符串中每个字符,foreach方法只是处理字符没有返回值。code

scala> "hello world".foreach(println)
h
e
l
l
o
 
w
o
r
l
d

使用for循环既能够实现map功能,也能够实现foreach功能,可是代码要比直接使用mapforeach复杂一些。字符串

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