Home > Software engineering >  split command in scala not working fine with special character like ~
split command in scala not working fine with special character like ~

Time:10-28

hi I have string like this :

var ma_test="~0.000000~~~"

I am using the split function with ~ as delimiter but it did not split correctly

what I try :

scala>  var ma_test="~0.000000~~~"
scala>  val split_val = ma_test.split("~")
    split_val: Array[String] = Array("", 0.000000)
scala>  val split_dis = split_val(2)
java.lang.ArrayIndexOutOfBoundsException: 2

... 32 elided

I try also to use val split_val = ma_test.split("\~") and ma_test.split('~') still not able to split correctly

CodePudding user response:

Using split will remove all the trailing empty strings, so there are 2 elements after split (as the leading ~ will also split), and starting from index 0, 1 etc..

Note that you get the first empty entry in the Array, as there is a ~ at the start that will also split, so you should use index 1.

var ma_test="~0.000000~~~"
val split_val = ma_test.split("~")
val split_dis = split_val(1)

Output

var ma_test: String = ~0.000000~~~
val split_val: Array[String] = Array("", 0.000000)
val split_dis: String = 0.000000

You can pass -1 as the second argument to see all parts, and using index 2 will then give you an empty string.

var ma_test="~0.000000~~~"
val split_val = ma_test.split("~", -1)
val split_dis = split_val(2)

Output

var ma_test: String = ~0.000000~~~
val split_val: Array[String] = Array("", 0.000000, "", "", "")
val split_dis: String = ""

CodePudding user response:

The output is the same with a "special character" ~ or the character x which suggests the the split function is not the issue. In either case if you try and access split_val(2) you will get an ArrayOutOfBoundsException since that index does not exist in the array. 0 or 1 will work ok.

scala> var ma_test="x0.000000xxx"
var ma_test: String = x0.000000xxx
                                                                                                                                                                                                                    
scala> ma_test.split("x")
val res1: Array[String] = Array("", 0.000000)

scala> var ma_test="~0.000000~~~"
var ma_test: String = ~0.000000~~~
                                                                                                                                                                                                                    
scala> ma_test.split("~")
val res0: Array[String] = Array("", 0.000000)
  • Related