Scala-字符串操作
package com.bigdata
object StringO {
def main(args: Array[String]): Unit = {
val s1 = "Hello"
val s2 = "World"
//拼接、合并字符串
println(s1 + " " + s2)
at(" "+s2))
//访问、截取字符串
println(s1(0))
val s3 = s1.substring(0,2)
println(s3)
//分隔字符串
val s4 = s1.split("ll")
println(s4)
//字符串格式化
val name = "xiaoming"
val age = 20
val s5 = "%s is %d years old".format(name,age)
println(s5)
//处理字符串中的字符(map,filter,flatmap,for,foreach)
val upper = s1.map(upper=&Upper)
val upper1 = s1.map(i=&Upper)
val upper2 = s1.map(_.toUpper)
println(upper,upper1,upper2)
val filter = s1.filter(i=>i !='o')
println(filter)
s1.foreach(println)
for (i <- s1 if i != 'l') {
println("i = "+i)
}
//字符串中的查模式
/
replaceall()/ 在⼀个string上调⽤.r⽅法可以创建⼀个Regex对象,之后在查是否含有⼀个匹配时就可以⽤findFirstIn,此⽅法返回option类型,当需要查是否完全匹配时可以⽤findAllIn,此⽅法返回⼀个迭代器 val pattern = "[0-9]+".r
val address = "101 main street 123"
val match1 = pattern.findFirstIn(address)
val match2 = pattern.findAllIn(address)
println(match1,match2)
//字符串中的替换模式(replaceAll replaceAllIn replaceFirst replaceFirstIn)
val address1 = placeAll("[0-9]","x")
println(address1)
//抽取String中模式匹配的部分
val pattern1 = "([0-9]+) ([A-Za-z]+)".r
val pattern1(count,fruit) = "100 bananas"
println(count,fruit)
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论