Search code examples
groovysplitsubstring

Groovy Split on Delimiter and Join Through nth Element


I'm a little bit newer to Groovy and trying to find the best way to split a delimited string. For example I have a string:

1/2/3/4/5/6/7

and I want basically a substring of that. So if I wanted 5 of those values retaining the delimiter my desired result would be

1/2/3/4/5

I've tried the code below which works on my online compiler but not in my actual application. It throws this error "No signature of method: static java.util.Arrays.copyOfRange() is applicable for argument types: ([Ljava.lang.String;, java.lang.Integer, java.lang.Long)"

inputString = "1/2/3/4/5/6/7";
stringDepth = 5;


stringArray = Arrays.copyOfRange(inputString.split("/"), 0, stringDepth);

stringPath = stringArray.join('/');

println "inputString="+inputString;
println "stringDepth="+stringDepth;
println "stringPath="+stringPath;

Solution

  • inputString.split('/').take(stringDepth).join('/')
    

    Should do it?