簡體   English   中英

Groovy:字符串到整數數組

[英]Groovy: String to integer array

我在Groovy中編碼,我有一個字符串參數“ X”,看起來像這樣:

899-921-876-123

現在,我成功地從中刪除了“-”

replaceAll("-", "")

現在,我想將此String分成多個單獨的數字-分成一個數組,例如(8,9,9 ...),以使用這些數字進行一些計算。 但是以某種方式,我不能像這樣同時拆分()這個字符串並使它成為一個整數:

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

所以當我嘗試類似的東西時:

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

我收到一個錯誤“找不到匹配的方法int#getAt(int)。請檢查聲明的類型是否正確以及該方法是否存在。” 或“找不到匹配的方法int#multiply(java.lang.String)。請檢查聲明的類型是否正確,如果不將方法轉換為Integer,請檢查方法”。

知道如何對這個字符串的單獨數字進行計算嗎?

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

replaceAll刪除所有非數字
collect在迭代迭代,並且將所有元素來int小號
String是其字符的迭代

鑒於您已經有了一串數字:

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

如果發現@cfrick,則使用最常見的解決方案。

這樣就完成了:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM