2013-04-17 30 views
1

我有一個字符串,例如「x(10,9,8)」我想從字符串中讀取每個整數,然後使用整數作爲數組索引從數組中檢索一個新的整數並用此值替換它。閱讀和替換字符串中的整數

我嘗試過的所有方法似乎都更適合將相同的事物應用於所有整數,或者只是檢索整數,然後放棄它們的跟蹤。任何人都可以告訴我這樣做的最佳方式嗎?

非常感謝。

+1

是否總是3個數字? – assylias

+0

你能不能給你試了一下代碼?你爲什麼不能解析字符串成臨時數組以避免丟失值? – Bulbasaur

+0

這就是案件搶劫案,不可以是1 - 4號 –

回答

1

使用正則表達式,您可以「瀏覽」字符串中的每個數字,而不管它們如何分隔,並根據需要進行替換。例如,下面的代碼打印x(101, 99, 88)

public static void main(String[] args) { 
    int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 88, 99, 101}; 
    String s = "x(10, 9, 8)"; 

    Pattern p = Pattern.compile("\\d+"); 
    Matcher m = p.matcher(s); 
    StringBuilder replace = new StringBuilder(); 
    int start = 0; 
    while(m.find()) { 
     //append the non-digit part first 
     replace.append(s.substring(start, m.start())); 
     start = m.end(); 
     //parse the number and append the number in the array at that index 
     int index = Integer.parseInt(m.group()); 
     replace.append(array[index]); 
    } 
    //append the end of the string 
    replace.append(s.substring(start, s.length())); 

    System.out.println(replace); 
} 

注意:你應該添加一些異常處理。

0

使用Integer.parseInt()String.split(",")String.indexOf()(用於()通過這個列表解析你的字符串的數字。與他們共創List

迭代並創建該數組中值的新名單。

迭代通過新的列表,並創建響應字符串。