美文网首页
Scala-1.字符串

Scala-1.字符串

作者: 悠扬前奏 | 来源:发表于2019-06-28 23:09 被阅读0次

    0 引言

    打印一个字符串的类型名,就是java.lang.String:

    scala> "hello".getClass.getName
    res0: String = java.lang.String
    

    Java的String类的方法就都可以用了。例如字符串长度和连接:

    scala> "hello".getClass.getName
    res0: String = java.lang.String
    
    scala> val s = "hello"
    s: String = hello
    
    scala> s.length
    res1: Int = 5
    
    scala> val s = "hello" + " world"
    s: String = hello world
    

    String类有StringOps类中的方法,例如foreach:

    scala> "hello".foreach(println)
    h
    e
    l
    l
    o
    

    for循环处理也可以:

    scala> for (c <- "hello") println(c)
    h
    e
    l
    l
    o
    

    也可以当做字符串序列:

    scala> "hello".getBytes.foreach(println)
    104
    101
    108
    108
    111
    

    1. 字符串相等

    和Java不同。Scala直接用==就行了,也不怕null,但是不能在null上调用方法:

    scala> "hello" == "hello"
    res7: Boolean = true
    
    scala> "hellp" == "h" + "llo"
    res8: Boolean = false
    
    scala> "hello" == "h" + "llo"
    res9: Boolean = false
    
    scala> "hello" == "h" + "ello"
    res10: Boolean = true
    
    scala> "hello" == "Hello".toLowerCase
    res11: Boolean = true
    
    scala> null == "hello"
    res12: Boolean = false
    
    scala> "hello" == null.toLowerCase
    <console>:12: error: value toLowerCase is not a member of Null
           "hello" == null.toLowerCase
    

    2. 创建多个字符串

    三个引号能创建多行字符串,甚至包含开头的空格。有一个stripMargin方法去掉编码时为了视觉方便添加的空格,该方法默认以|作为标志,可以设定参数。

    scala> val s1 = """ This is
         | a Mulitline
         | String"""
    s1: String =
    " This is
    a Mulitline
    String"
    
    scala> val s2 = """This is 
         |                  #a Multiline
         |                  #line""".stripMargin('#')
    s2: String =
    This is
    a Multiline
    line
    

    3. 分隔字符串

    和很多其他语言一样,用split,不同的使用细节会有一些不同的结果,不详述:

    scala> "hello world".split(" ")
    res14: Array[String] = Array(hello, world)
    

    4. 变量替换

    就是格式化吧,java中format的一套:

    scala> val name = "John"
    name: String = John
    
    scala> val age = 28
    age: Int = 28
    
    scala> println(s"$name is $age years old")
    John is 28 years old
    

    可以再字符串变量汇总使用表达式:

    scala> println(s"Age next year ${age + 1}")
    Age next year 29
    scala> println(s"Age next year are 30 are ${age==30}")
    Age next year are 30 are false
    

    表达式可以用于对类的成员引用:

    scala> println(s"A student named ${hanna.name} has a score of ${hanna.score}" )
    A student named hanna has a score of 95
    

    s实际上是一个方法,类似的方法就还有f:

    scala> println(f"A student named ${hanna.name} has a score of ${hanna.score}%.1f")
    A student named hanna has a score of 95.0
    

    raw插入符不转义

    scala> println(raw"foo\bar")
    foo\bar
    

    格式化常用符:
    %c %d %e %f %I %o %s %u %x %% %

    相关文章

      网友评论

          本文标题:Scala-1.字符串

          本文链接:https://www.haomeiwen.com/subject/ghajcctx.html