A Scala split String example

Scala String FAQ: How do I split a String in Scala?

Short answer: Because Scala strings are Java String instances, you use the split method of the Java String class, like this:

val nameValuePairs = result.split("&")

Or, if you prefer the infix syntax, you can use this equivalent statement:

val nameValuePairs = result split "&"

Longer answer:

While working with the Yahoo OAuth API, I ran into a situation where I needed to split a String in Scala to get the information I needed in the response from Yahoo. In short, the Yahoo OAuth web service sent me a text string back that looks like this:

oauth_token=FOO&oauth_token_secret=BAR&oauth_expires_in=3600

I needed to split that string by the "&" character, and then deal with each name/value pair in my code (where the name/value pairs are separated by the "=" character.)

Because a Scala String is really just a Java String, you just use the Java String split method, as shown in this short Scala REPL session:

scala> val result = "oauth_token=FOO&oauth_token_secret=BAR&oauth_expires_in=3600"                                        
result: java.lang.String = oauth_token=FOO&oauth_token_secret=BAR&oauth_expires_in=3600

scala> val nameValuePairs = result.split("&")
nameValuePairs: Array[java.lang.String] = Array(oauth_token=FOO, oauth_token_secret=BAR, oauth_expires_in=3600)

As you can see in the second line, I call the split function, telling it to use the "&" character to split my string into multiple strings. As you can see from the Scala REPL output, the variable nameValuePairs is an array of String type, and in this case, these are the name/value pairs I wanted.

Post new comment

The content of this field is kept private and will not be shown publicly.