Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get first 2 values in a comma separated string

Tags:

scala

I am trying to get the first 2 values of a comma separated string in scala. For example

a,b,this is a test

How do i store the values a,b in 2 separate variables?

like image 216
Siva Avatar asked Sep 29 '14 11:09

Siva


People also ask

How do you separate a string split by a comma?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you get comma separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you split in Scala?

Use the split() Method to Split a String in Scala Scala provides a method called split() , which is used to split a given string into an array of strings using the delimiter passed as a parameter. This is optional, but we can also limit the total number of elements of the resultant array using the limit parameter.


1 Answers

To keep it easy and clean.

KISS solution:

1.Use split for separation. Then use take which is defined on all ordered sequences to get the elements as needed:

scala> val res = "a,b,this is a test" split ',' take 2
res: Array[String] = Array(a, b)

2.Use Pattern matching to set the variables:

scala> val Array(x,y) = res
x: String = a
y: String = b*
like image 119
Andreas Neumann Avatar answered Sep 27 '22 17:09

Andreas Neumann