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
1.1k views
in Technique[技术] by (71.8m points)

scala - How to split string with trailing empty strings in result?

I am a bit confused about Scala string split behaviour as it does not work consistently and some list elements are missing. For example, if I have a CSV string with 4 columns and 1 missing element.

"elem1, elem2,,elem 4".split(",") = List("elem1", "elem2", "", "elem4")

Great! That's what I would expect.

On the other hand, if both element 3 and 4 are missing then:

"elem1, elem2,,".split(",") = List("elem1", "elem2")

Whereas I would expect it to return

"elem1, elem2,,".split(",") = List("elem1", "elem2", "", "")

Am I missing something?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As Peter mentioned in his answer, "string".split(), in both Java and Scala, does not return trailing empty strings by default.

You can, however, specify for it to return trailing empty strings by passing in a second parameter, like this:

String s = "elem1,elem2,,";
String[] tokens = s.split(",", -1);

And that will get you the expected result.

You can find the related Java doc here.


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

...