Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

scala - muliline string split

I have this:

val msg = "Preparado para cocinar..."
val message = msg.splitAt(msg.length()/2)

println(message._1 + "
" + message._2.trim())

The problem is that I am getting this result (bcz I am just spliting it at the middle):

Preparado pa
ra cocinar...

How I can have a multi(not only in 2 parts) displayed message but it should be separated in spaces not in the middle of the sentence?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A not very elegant working solution,

val a = msg.split("\s")  // Split by space
a = Array(Preparado, para, cocinar...)

val n = a.size / 2  // Get halving point rounded to lower closest integer
n = 1

val b = Array(a.take(n).mkString, a.drop(n).mkString(" "))  // Halve the array
b = Array(Preparado, para cocinar...)

b.foreach(println)  // Print it
Preparado
para cocinar...

Update

As pointed out by @AdrienAubel, consider the use of splitAt over the split array,

val (b1,b2) = a.splitAt(n)
b1 = Array(Preparado)
b2 = Array(para, cocinar...)

println(b1.mkString(" "))
Preparado

println(b2.mkString(" "))
para cocinar...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...