将文本赋值给一个字符串变量,比如:
val text = "Get Spark from the downloads page of the project website. This documentation is for Spark version 2.4.5. Spark uses Hadoop’s client libraries for HDFS and YARN. Downloads are pre-packaged for a handful of popular Hadoop versions. Users can also download a “Hadoop free” binary and run Spark with any Hadoop version by augmenting Spark’s classpath. Scala and Java users can include Spark in their projects using its Maven coordinates and in the future Python users can also install Spark from PyPI."
使用字符串的 count 方法来计算 "Spark" 出现的次数,比如:
val count = text.split("Spark").length - 1
这里使用了字符串的 split 方法将字符串按照 "Spark" 分割成多个子串,然后计算子串个数减去 1 就是 "Spark" 出现的次数。
输出结果,比如:
println(s""""Spark" occurs $count times in the text.""")
完整的程序如下:
object Main extends App {
val text = "Get Spark from the downloads page of the project website. This documentation is for Spark version 2.4.5. Spark uses Hadoop’s client libraries for HDFS and YARN. Downloads are pre-packaged for a handful of popular Hadoop versions. Users can also download a “Hadoop free” binary and run Spark with any Hadoop version by augmenting Spark’s classpath. Scala and Java users can include Spark in their projects using its Maven coordinates and in the future Python users can also install Spark from PyPI."
val count = text.split("Spark").length - 1
println(s""""Spark" occurs $count times in the text.""")
}
输出结果为:
"Spark" occurs 4 times in the text.
希望这个回答能够帮到您!