简体   繁体   中英

Groovy: String to integer array

Im coding in Groovy and I have a string parameter "X" which looks like this:

899-921-876-123

For now i succesfully removed the "-" from it by

replaceAll("-", "")

And now I want to divide this String into separete numbers - to an array, like (8,9,9...) to make some calculations using those numbers. But somehow I cannot split() this String and make it an Integer at the same time like that:

assert X.split("")
def XInt = Integer.parseInt(X)

So then when Im trying something like:

def  sum = (6* X[0]+ 5 * X[1] + 7 * X[2])

I get an error that "Cannot find matching method int#getAt(int). Please check if the declared type is right and if the method exists." or "Cannot find matching method int#multiply(java.lang.String). Please check if the declared type is right and if the method " if im not converting it to Integer...

Any idea how can I just do calculations on separate numbers of this string?

def X = '899-921-876-123'
def XInt = X.replaceAll(/\D++/, '').collect { it as int }
assert XInt == [8, 9, 9, 9, 2, 1, 8, 7, 6, 1, 2, 3]
assert 6* XInt[0]+ 5 * XInt[1] + 7 * XInt[2] == 6* 8+ 5 * 9 + 7 * 9

the replaceAll removes all non-digits
the collect iterates over the iterable and converts all elements to int s
a String is an iterable of its characters

Given you already just have a string of numbers:

"123"*.toLong() // or toShort(), toInteger(), ...
// ===> [1, 2, 3]

If found @cfrick approach the most grooviest solution.

This makes it complete:

def n = "899-921-876-123".replaceAll("-", "")
print n*.toInteger()

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