简体   繁体   中英

Accessing parts of splitted string in scala

I am working on a scala application. I have a string as follows:

val str = abc,def,xyz

I want to split this string and access splitted parts separately like abc , def and xyx. My code is as follows

val splittedString = str.split(',')

to access each part of this splitted string I am trying something like this splittedString._1, splittedString._2, splittedString._3 . But intellij is giving me error stating " cannot resolve symbol _1 " and same error for part 2 and 3 as well. How can I access each element of splitted string?

The method split is defined over String s to return an Array[String] .

What you can do is access by (zero-based) index, splittedString(0) being the first item.

Alternatively, if you know the length of resulting array you want to obtain , you can convert it to a tuple and access with the accessor methods you were referring to:

val tuple =
  str.split(",") match {
    case Array(a, b, c) => (a, b, c)
    case _ => throw new IllegalArgumentException
  }

tuple._1 will now contain abc in your example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM