我需要寫一個Spark Scala代碼來拆分字符串。我的分隔符是雙管(||)。如果最後一個字段爲空,分割會給出ArrayIndexOutOfBoundsException。有人可以幫我解決這個問題。僅當最後一個字段爲空時,纔會發生此問題。這裏是我的代碼:scala拆分雙管道(||)不打印最後一列如果爲空
val str1 = "one||two||three||"
val splitfields1 = str1.split("\\|\\|")
println(splitfields1(2))
//output : three
val str2 = "one||||three||"
val splitfields2 = str2.split("\\|\\|")
println(splitfields2(2))
println(splitfields2(1))
// output1 : three
// output2 : Empty line
val str3 = "one||two||||"
val splitfields3 = str3.split("\\|\\|")
println(splitfields3(2))
// Error : java.lang.ArrayIndexOutOfBoundsException: 2
// I expected field number 2 will have null/empty string and wont give outofbound exception
splitfields3.foreach { println }
//Output : one
two
//Here it is not printing empty line
如何解決這個問題。我從文件中獲取輸入,所以它可以在任何位置都有空字段。
https://stackoverflow.com/questions/27689065/how-to-split-string-with-trailing-empty-strings-in-result –