1_scala_字符串操作

//string compare
val s1 = "Hello"
val s2 = "h" + "ello"

println("'" + s1 + "' equal to " + "'" + s2 + "' is " + (s1 == s2))
println(s1.toUpperCase == s2.toUpperCase)
println()

//multiline string
val foo = """This is
    a multiline
    String"""

val foo1 = """This is
a multiline
String""".replaceAll("\n", " ")

val foo2 = """This is
|a multiline
|String""".stripMargin


println(foo)
println(foo1)
println(foo2)
println()


//split string
val sp1 = "eggs, milk, butter, Coco Puffs"
sp1.split(",").foreach(println)
sp1.split(",").map(_.trim).foreach(println)

println()

//string interpolation(n. 插入,篡改)
val name = "Fred"
val age = 33
val weight = 63.00

println(s"$name is $age years old, and weight $weight Kg")
println(s"Age next year: ${age+1}")
println(s"You are 33 years old: ${age == 33}")

case class Student(name: String, score: Int)
val eric = Student("Eric", 99)
println(s"${eric.name} has a score of ${eric.score}")

println(f"$name is $age years old, and weight $weight%.2f Kg")
val info = f"$name is $age years old, and weight $weight%.0f Kg"
println(info)

println("Eric\nChan")
println(raw"Eric\nChan")

//prior to scala 2.10
println("%s is %d years old".format(name, age))
println()

//string character processing
val upper = "hello, World".map(c => c.toUpper)
val upper1 = "hello, World".filter(_ != 'l').map(_.toUpper)
val upper2 = for( c <- "hello, World") yield c.toUpper
val upper3 = for {
    c <- "hello, World"
    if c != 'l'
} yield c.toUpper
println(upper)
println(upper1)
println(upper2)
println(upper3)

def toLower(c : Char) : Char = (c.toByte+32).toChar
val lower = "HELLO".map(toLower)
println(lower)

val toLower1 = (c : Char) => (c.toByte+32).toChar
val lower1 = for (c <- "WORLD") yield toLower1(c)
println(lower1)
println()

//pattern match
val numPattern = "[0-9]+".r
val addr = "123 main street suite 109"
val match1 = numPattern.findFirstIn(addr)
println(match1 + " " + match1.get)
val matches = numPattern.findAllIn(addr)
println(matches)
matches.foreach(println)
import scala.util.matching.Regex
val numPattern1 = new Regex("[0-9]+")
println(numPattern1.getClass.getName)

val addrReplace = addr.replaceAll("[0-9]", "x")
println(addrReplace)
val addrReplaceFirst = addr.replaceFirst("[0-9]", "x")
println(addrReplaceFirst)
val regex = "H".r
val newAddr = regex.replaceFirstIn("Hello,world", "J")
println(newAddr)

val pattern = "([0-9]+) ([a-zA-Z]+)".r
val pattern(count, fruit) = "100 Bananas"
println(pattern)
println(count + " " + fruit)
println()

//get character
println("hello".charAt(0))
println("hello"(1))
println("hello".apply(2))
println()

//implicit class
object StringUtil {
    implicit class StringImprovements(val s: String) {
        def increment: String = s.map(c => (c + 1).toChar)
        def decrement: String = s.map(c => (c - 1).toChar)
        def hideAll: String = s.replaceAll(".", "*")
        def plusOne: Int = s.toInt + 1
        def asBoolean: Boolean = s match {
            case "0" | "zero" | "" | " " => false
            case _ => true
        }
    }
}

import StringUtil._
println("HAL".increment)
println("IBM".decrement)
println("123456".hideAll)
println("4".plusOne)
println("0".asBoolean)
//raise NumberFormatException
//println("a".plusOne)


/**
* Calculate the Adler-32 checksum using Scala.
* @see http://en.wikipedia.org/wiki/Adler-32
*/

object Adler32Checksum {
    val BASE = 65521

    def main(args: Array[String]) {
        val sum = adler32Sum("Wikipedia")
        printf("checksum (int) = %d\n", sum)
        printf("checksum (hex) = %s\n", sum.toHexString)
    }

    def adler32Sum(s: String): Int = {
        var a = 1
        var b = 0

        s.getBytes.foreach{ char =>
            a = (a + char) % BASE
            b = (a + b) % BASE
        }

        (b << 16) + a
    }
}


你可能感兴趣的:(scala/java)