Files and Text Processing
Counting Words
Count words, characters, and letters in text.
word-count
Splitting on spaces counts words, `length` counts characters, and removing the spaces first counts only the letters.
Counting Words
WordCount.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val text = "the quick brown fox"
val words = text.split(" ").toList
val chars = text.length
val letters = text.replace(" ", "").length
println("words=" + words.length)
println("chars=" + chars)
println("letters=" + letters)
}
}
object Main {
def main(args: Array[String]): Unit = {
val text = "hello world"
val words = text.split(" ").toList
val chars = text.length
val letters = text.replace(" ", "").length
println("words=" + words.length)
println("chars=" + chars)
println("letters=" + letters)
}
}
object Main {
def main(args: Array[String]): Unit = {
val text = "one two three"
val words = text.split(" ").toList
val chars = text.length
val letters = text.replace(" ", "").length
println("words=" + words.length)
println("chars=" + chars)
println("letters=" + letters)
}
}
text ← the quick brown fox, words ← List(the, quick, brown, fox)
1object Main {2 def main(args: Array[String]): Unit = {3 val text→ the quick brown fox = "the quick brown fox" //@text="hello world", "one two three"4 val words→ List(the, quick, brown, fox) = textthe quick brown fox.split(" ").toList5 val chars→ 19 = text.length→ 196 val letters→ 16 = textthe quick brown fox.replace(" ", "").length78 println("words=" + words.length4)9 println("chars=" + chars19)10 println("letters=" + letters16)11 }12}outputwords=4 chars=19 letters=16
text ← hello world, words ← List(hello, world), chars ← 11, text.length ← 11
1object Main {2 def main(args: Array[String]): Unit = {3 val text→ hello world = "hello world"4 val words→ List(hello, world) = texthello world.split(" ").toList5 val chars→ 11 = text.length→ 116 val letters→ 10 = texthello world.replace(" ", "").length78 println("words=" + words.length2)9 println("chars=" + chars11)10 println("letters=" + letters10)11 }12}outputwords=2 chars=11 letters=10
text ← one two three, words ← List(one, two, three), chars ← 13
1object Main {2 def main(args: Array[String]): Unit = {3 val text→ one two three = "one two three"4 val words→ List(one, two, three) = textone two three.split(" ").toList5 val chars→ 13 = text.length→ 136 val letters→ 11 = textone two three.replace(" ", "").length78 println("words=" + words.length3)9 println("chars=" + chars13)10 println("letters=" + letters11)11 }12}outputwords=3 chars=13 letters=11