0

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?

0

3 Answers 3

4
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 ints
a String is an iterable of its characters

Sign up to request clarification or add additional context in comments.

Comments

1

Given you already just have a string of numbers:

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

2 Comments

A split is not necessary, a String is an iterable of its characters, so you can directly use collect. Converting to long is a bit overkill if you only have single digits and using the Groovy magic with as ... is better anyway. ;-)
@Vampire Thanks, changed it
1

If found @cfrick approach the most grooviest solution.

This makes it complete:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.