scala--String

All Scala variables are declared as a val or var.
eg:val s = "Hello, world"等价于java语法final String s = “Hello, world”,尽量使用val不用var
val s: String = “Hello, world” ,语法成立但是不推荐,因为看起来允长,val s: String = someObject.someMethod(42)是推荐的,因为不能明确一眼看出来返回类型

字符串是字符序列Seq[Char],所有Seq[Char]方法可以直接用在字符串上.

val s = “foo bar baz”
s.count(_ == ‘a’) // 2
s.dropRight(2) // foo bar b
s.dropWhile(_ != ‘b’) // bar baz
s.filter(_ != ‘o’) // f bar baz
s.sortWith(_ < ) // " aabbfoorz"
s.take(3) // foo
s.takeRight(3) // baz
s.takeWhile(
!= ‘r’) // foo ba

连接方法一起

“scala”.drop(2).take(2).capitalize //Al
String类可以用java的java.lang.String类方法,以及scala的StringOps类方法,比如drop, take和 filter
Predef 源码值得了解

测试String相等

val s1 = “Hello”
val s2 = “Hello”
val s3 = “H” + “ello”
s1 == s2 // true
s1 == s3 // true
val s4: String = null // String = null
s3 == s4 // false
s4 == s3 // false,不会抛出异常

val a = “Kimberly”
val b = “kimberly”
a.equalsIgnoreCase(b) // true

val s1: String = null
val s2: String = null
s1.toUpperCase == s2.toUpperCase//java.lang.NullPointerException

==方法定义在AnyRef 类中,首先检查null值,然后调用第一个对象的equals 方法
Option代替null
val foo = “”“This is
a multiline
String”""
val speech = “”“Four score and
|seven years ago”"".stripMargin
val speech = “”“Four score and
#seven years ago”"".stripMargin(’#’)
val foo = “”“Four score and
seven years ago”""
val speech = “”“Four score and
|seven years ago
|our fathers …”"".stripMargin.replaceAll("\n", " “)
val s = “”“This is known as a
|“multiline” string
|or ‘heredoc’ syntax.””". stripMargin.replaceAll("\n", " “)
“hello world”.split(” “)
“Relax, nothing is under control”.split(”\s+")
“hello world”.split(" ") //Array(hello, world)
“hello world”.split(’ ') //Array(hello, world)

标题

val name = “Fred”
val age = 33
val weight = 200.00
println(s"$name is $age years old, and weighs $weight pounds.")//Fred is 33 years old, and weighs 200.0 pounds.

scala> println(s"Age next year: ${age + 1}")
Age next year: 34

scala> println(s"You are 33 years old: ${age == 33}")
You are 33 years old: true

case class Student(name: String, score: Int)
val hannah = Student(“Hannah”, 95)
scala> println(s"${hannah.name} has a score of ${hannah.score}")
Hannah has a score of 95

scala> println(s"$hannah.name has a score of $hannah.score")
Student(Hannah,95).name has a score of Student(Hannah,95).score

scala> println(f"$name is $age years old, and weighs $weight%.2f pounds.")
Fred is 33 years old, and weighs 200.00 pounds.

scala> println(f"$name is $age years old, and weighs $weight%.0f pounds.")
Fred is 33 years old, and weighs 200 pounds.

scala> val s = f"$name, you weigh $weight%.0f pounds."
s: String = Fred, you weigh 200 pounds.

scala> s"foo\nbar"
res0: String =
foo
bar

scala> raw"foo\nbar"
res1: String = foo\nbar

val h = "Hello"
f"'$h%s'"       // 'Hello'
f"'$h%10s'"     // '     Hello'
f"'$h%-10s'"    // 'Hello     '
f"'${h}%s'"       // 'Hello'
f"'${h}%10s'"     // '     Hello'
f"'${h}%-10s'"    // 'Hello     '

val a = 10.3456         // a: Double = 10.3456
val b = 101234567.3456  // b: Double = 1.012345673456E8
f"'${a}%.1f'"     // '10.3'
f"'${a}%.2f'"     // '10.35'
f"'${a}%8.2f'"    // '   10.35'
f"'${a}%8.4f'"    // ' 10.3456'
f"'${a}%08.2f'"   // '00010.35'
f"'${a}%-8.2f'"   // '10.35   '
f"'${b}%-2.2f'"   // '101234567.35'
f"'${b}%-8.2f'"   // '101234567.35'
f"'${b}%-14.2f'"  // '101234567.35  '

val c = 10.5f     // c: Float = 10.5
f"'${c}%.1f'"     // '10.5'
f"'${c}%.2f'"     // '10.50'

val ten = 10
f"'${ten}%d'"         // '10'
f"'${ten}%5d'"        // '   10'
f"'${ten}%-5d'"       // '10   '

val maxInt = Int.MaxValue
f"'${maxInt}%5d'"     // '2147483647'

val maxLong = Long.MaxValue
f"'${maxLong}%5d'"    // '9223372036854775807'
f"'${maxLong}%22d'"   // '   9223372036854775807'

val zero = 0
val one = 1
val negTen = -10
val bigPos = 12345
val bigNeg = -12345
val maxInt = Int.MaxValue

// non-negative integers
f"${zero}%03d"      // 000
f"${one}%03d"       // 001
f"${bigPos}%03d"    // 12345
f"${bigPos}%08d"    // 00012345
f"${maxInt}%08d"    // 2147483647
f"${maxInt}%012d"   // 002147483647

// negative integers
f"${negTen}%03d"    // -10
f"${negTen}%05d"    // -0010
f"${bigNeg}%03d"    // -12345
f"${bigNeg}%08d"    // -0012345

val s = 's'
f"|${s}%c|"     // |s|
f"|${s}%5c|"    // |    s|
f"|${s}%-5c|"   // |s    |

val n = "Al"
val w = 200.0
val s = f"""Hi, my name is ${n}
  |and I weigh ${w}%.1f pounds.
  |""".stripMargin.replaceAll("\n", " ")
println(s) Hi, my name is Al and I weigh 200.0 pounds.

println(f"%%")   // prints %
println(f"$$")   // prints $

scala> val upper = for c <- “yo, adrian” yield c.toUpper
upper: String = YO, ADRIAN

scala> val upper = “yo, adrian”.map(c => c.toUpper)
upper: String = YO, ADRIAN

scala> val upper = “yo, adrian”.map(_.toUpper)
upper: String = YO, ADRIAN

“yo, adrian”.filter(_ != ‘a’).map(_.toUpper) // String = YO, DRIN

scala> for c <- “hello” do println©
h
e
l
l
o

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

scala> “hello”.getBytes
res0: Array[Byte] = Array(104, 101, 108, 108, 111)

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

val upper = for c <- “hello, world” yield c.toUpper

val result = “hello, world”
.filter(_ != ‘l’)
.map(_.toUpper) 等于
val result = for
c <- “hello, world”
if c != ‘l’
yield
c.toUpper

val x = “HELLO”.map { c =>
// ‘c’ represents each character from “HELLO” (‘H’, ‘E’, etc.)
// that’s passed one at a time into this algorithm
val i: Int = c.toByte + 32
i.toChar
}
// x: String = “hello”

val f = “foo bar baz”
f.dropWhile(_ != ’ ') // " bar baz"
f.filter(_ != ‘a’) // foo br bz
f.takeWhile(_ != ‘r’) // foo ba

标题

val numPattern = “[0-9]+”.r
val address = “123 Main Street Suite 101”
scala> val match1 = numPattern.findFirstIn(address)
match1: Option[String] = Some(123)
scala> val matches = numPattern.findAllIn(address)
val matches: scala.util.matching.Regex.MatchIterator =
scala> matches.foreach(println)
123
101

另一种方式
import scala.util.matching.Regex
val numPattern = Regex("[0-9]+")
val address = “123 Main Street Suite 101”
val match1 = numPattern.findFirstIn(address) // Option[String] = Some(123)
返回值是Some[String] 或 None.

scala> val address = “123 Main Street”.replaceAll("[0-9]", “x”)
address: String = xxx Main Street

scala> val regex = “[0-9]”.r
regex: scala.util.matching.Regex = [0-9]
scala> val newAddress = regex.replaceAllIn(“123 Main Street”, “x”)
newAddress: String = xxx Main Street

scala> val result = “123”.replaceFirst("[0-9]", “x”)
result: String = x23

scala> val regex = “H”.r
regex: scala.util.matching.Regex = H
scala> val result = regex.replaceFirstIn(“Hello world”, “J”)
result: String = Jello world

val pattern = “([0-9]+) ([A-Za-z]+)”.r
val pattern(count, fruit) = “100 Bananas”
// count: String = 100
// fruit: String = Bananas

“movies near 80301”
“movies 80301”
“80301 movies”
“movie: 80301”
“movies: 80301”
“movies near boulder, co”
“movies near boulder, colorado”
val MoviesZipRE = “movies (\d{5})”.r
val MoviesNearCityStateRE = “movies near ([a-z]+), ([a-z]{2})”.r
val results = textUserTyped match
case MoviesZipRE(zip) => getSearchResults(zip)
case MoviesNearCityStateRE(city, state) => getSearchResults(city, state)
case _ => None

“hello”(0) // Char = h
“hello”(1) // Char = e
“hello”(99) // throws java.lang.StringIndexOutOfBoundsException
“hello”(1)等价于"hello".apply(1)

//以下有点累赘不建议
“hello”.charAt(0) // Char = h
“hello”.charAt(99) // throws java.lang.StringIndexOutOfBoundsException

import scala.util.Random
// examples of two random alphanumeric strings
Random.alphanumeric.take(10).mkString // 7qowB9jjPt
Random.alphanumeric.take(10).mkString // a0WylvJKmX
A-Z, a-z, 和0-9组成的随机字符串

val r = scala.util.Random
val randomSeq = for (i <- 0 to r.nextInt(10)) yield r.nextPrintableChar
randomSeq.mkString // @Wvz#y#Rj
randomSeq.mkString //b0F:P&!WT$
包含 ASCII 范围33-126之间的任意字符,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值