简体   繁体   English

Groovy:字符串到整数数组

[英]Groovy: String to integer array

Im coding in Groovy and I have a string parameter "X" which looks like this: 我在Groovy中编码,我有一个字符串参数“ X”,看起来像这样:

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. 现在,我想将此String分成多个单独的数字-分成一个数组,例如(8,9,9 ...),以使用这些数字进行一些计算。 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." 我收到一个错误“找不到匹配的方法int#getAt(int)。请检查声明的类型是否正确以及该方法是否存在。” 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... 或“找不到匹配的方法int#multiply(java.lang.String)。请检查声明的类型是否正确,如果不将方法转换为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 replaceAll删除所有非数字
the collect iterates over the iterable and converts all elements to int s collect在迭代迭代,并且将所有元素来int小号
a String is an iterable of its characters String是其字符的迭代

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. 如果发现@cfrick,则使用最常见的解决方案。

This makes it complete: 这样就完成了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM