Splitting String with delimiter

StringGroovySplit

String Problem Overview


I am currently trying to split a string 1128-2 so that I can have two separate values. For example, value1: 1128 and value2: 2, so that I can then use each value separately. I have tried split() but with no success. Is there a specific way Grails handles this, or a better way of doing it?

String Solutions


Solution 1 - String

Try:

def (value1, value2) = '1128-2'.tokenize( '-' )

Solution 2 - String

How are you calling split? It works like this:

def values = '1182-2'.split('-')
assert values[0] == '1182'
assert values[1] == '2'

Solution 3 - String

def (value1, value2) = '1128-2'.split('-') should work.

Can anyone please try this in Groovy Console?

def (v, z) =  '1128-2'.split('-')

assert v == '1128'
assert z == '2'

Solution 4 - String

You can also do:

Integer a = '1182-2'.split('-')[0] as Integer
Integer b = '1182-2'.split('-')[1] as Integer

//a=1182 b=2

Solution 5 - String

split doesn't work that way in groovy. you have to use tokenize...

See the docs:

http://groovy-lang.org/gdk.html#split()

Solution 6 - String

dependencies {
   compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
     ['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
       def (g, m) = i.tokenize( ':' )
       dep.exclude group: g  , module: m
     }
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionthehoule64View Question on Stackoverflow
Solution 1 - Stringtim_yatesView Answer on Stackoverflow
Solution 2 - StringataylorView Answer on Stackoverflow
Solution 3 - StringdmahapatroView Answer on Stackoverflow
Solution 4 - StringdavidddpView Answer on Stackoverflow
Solution 5 - StringAngstrom BeebeView Answer on Stackoverflow
Solution 6 - StringqwasView Answer on Stackoverflow