2012-08-27 23 views
3

Someone on stackoverflow給出了此代碼以查找字符的位置......現在問題是,它是一個循環,它搜索整個字符串並返回每個位置......現在,這段代碼使用了一個「池」的例子。因此,它返回1和2如何使用索引循環根據位置替換字符

String s = "Pool"; 
int idx = s.indexOf('o'); 
while (idx > -1) { 
System.out.println(idx); 
idx = s.indexOf('o', idx + 1); 
} 

有沒有辦法使用的方法返回兩個位置,更換字符...例如,如果我想用「HH」,以取代「O」產生「的方式phhl'

+0

如果用替換「池」「O」「HH」,你會得到「phhhhl」 – n00begon

+0

我不想更換「O」我想更換位置1和2 –

+0

我不想根據字符替換,我想根據位置替換 –

回答

2

我會建議由@Sujay的解決方案,但以防萬一不符合您的要求...

int counter = 0; 
String input = "Pool"; 
char replacement = 'l'; 
char[] inputArray = input.toCharArray(); 
for(char ch : inputArray) { 
    if(ch == 'o') { 
     inputArray[counter] = replacement; 
    } 
    counter += 1; 
} 
String output = new String(inputArray); 
System.out.println(output);