Scala编程实战—字符串

来源:互联网 发布:随机抽取数字软件 编辑:程序博客网 时间:2024/04/27 20:08

作者:WenWu_Both
出处:http://blog.csdn.net/wenwu_both/article/
版权:本文版权归作者和CSDN博客共有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文链接;否则必究法律责任

1.测试字符串的相等性

val s1 = "Hello"val s2 = "Hello"val s3 = "H" + "ello"s1 == s2 // return:Trues2 == s3 // return:True

不考虑字符大小写的话,可以将比较字符串先统一转换成大写或小写,再进行”==”操作:

val s1 = "hello"val s2 = "Hello"s1.toUpperCase == s2.toUpperCase // return: True

也可以退而求其次,使用Java字符串类的equalsIngoreCase方法

val s1 = "hello"val s2 = "Hello"s1.equalsIgnoreCase(s2) // return: True

2.创建多行字符串

在Scala中可以用3个双引号创建多行字符串

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

3.分隔字符串

使用大名鼎鼎的split命令

"Hello,World".split(",") // return: Array(Hello, World)

split方法接受正则表达式:

"hello world, this is Al".split("\\s+") // return: Array(hello, world, this, is, Al)

分隔并实现各要素头尾空格的去除:

"aaa, bbb,ccc, ddd ".split(",").map(_.trim) // trim命令为去除字符串头尾空格

进一步可以通过replaceAll的方法实现字符串要素中所有空格的去除:

"aa b,ccc , d d d".split(",") // return: Array(aa b,ccc , d d d)"aa b,ccc , d d d".split(",").map(_.replaceAll(" ","")) // return: Array(aab,ccc,ddd)

4.字符串中的变量代换

本质上就是格式化字符串。

(1)字符串前加字母”s”,字符串中的变量前添加”$”

val name = "Tom"val age = 18println(s"$name is $age years old!") // return: Tom is 18 years old!

在字符串中使用变量表达式时,需要用{}包裹:

val age = 18println(s"Age next year:${age + 1}") // return: Age next year:19

同时,访问对象的属性时,也要求用{}包裹:

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

(2)字符串前加字母”f”,字符串中的变量前添加”$”,变量后添加”%”设置格式:

val name = "Fred"val weight = 200.00println(f"$name weghts $weght%.0f pounds!")

(3)format方法(类似于Python中的格式化字符串)

println("%s is %d years old".format(name, age)) 

printf的格式化常用符:

  • %c:字符
  • %d:十进制数字
  • %e:指数浮点数
  • %f:浮点数
  • %i:整数(十进制)
  • %o:八进制数
  • %s:字符串
  • %u:无符号十进制数
  • %x:十六进制数
  • %%:打印一个百分号
  • \%:打印一个百分号

去除转义,可在字符串前添加”raw”

println(raw"foo\nbar")

5.遍历字符串

(1)map方法

val upper = "hello, world".map(c => c.toUpper)val upper = "hello, world".map(_.toUpper)// 与filter过滤器组合使用val upper = "hello, world".filter(_ != 'l').map(_.toUpper)// 注意'l'为Char,而非String,故为单引号,双引号会报错

(2)for…yield

val upper = for (c <- "hello, world")yield c.toUpper

在for循环添加yield实际上是将每次循环的结果放到临时存放区中,当循环结束的时候,在临时存放区中的所有元素以一个集合的形式返回,其作用与map方法等同。

(3)foreach

循环打印:

"hello, world"foreach(println)

6.字符串中的查找模式

判断字符串是否符合某个正则表达式。

匹配数字:

val numPattern = "[0-9]+".rval address = "123 Main Street Suite 101"val match1 = numPattern.findFirstIn(address) // 第一个匹配的数字,返回:Option[String] = Some(123)val matchs = numPattern.findAllIn(address)  // 返回的迭代器val matchs = numPattern.findAllIn(address).toArray // 返回数组 

上面实例是通过字符串后面添加”.r”的方式创建正则表达式的,另外一种方式是引入Regex类

import scala.util.matching.Regexvar numPattern = new Regex("[0-9]+")

7.抽取String中模式匹配的部分

// 定义期望的模式val pattern = "([0-9]+) ([A-Za-z]+)".r// 从目标字符串中提取正则组val pattern(count, fruit) = "100 Bananas"

8.访问字符串中的字符中的一个字符

(1)Java的charAt方法

"hello".charAt(0)

(2)Scala的数组方法

"hello"(0)
原创粉丝点击