2012-04-03 18 views
5

crescente voglio sostituire "a" di "abababababababab" con 001.002.003,004 mila ...... che è "001b002b003b004b005b ....."Java sostituire stringa con il numero

int n=1 
String test="ababababab"; 
int lo=test.lastIndexOf("a"); 
while(n++<=lo) Abstract=Abstract.replaceFirst("a",change(n)); 
//change is another function to return a string "00"+n; 

tuttavia questo è povero efficienza, quando la stringa è abbastanza grande, ci vorranno minuti!

avete un modo efficiente? grazie mille!

+0

Qual è la dimensione massima della stringa, 999 volte un 'a'? (dato che hai solo tre cifre) – jb10210

+0

sì, file.problem molto grande risolto, grazie. – chandler

risposta

8

Utilizzare un Matcher per trovare e sostituire le a s:

public static void main(String[] args) { 

    Matcher m = Pattern.compile("a").matcher("abababababababab"); 

    StringBuffer sb = new StringBuffer(); 
    int i = 1; 
    while (m.find()) 
     m.appendReplacement(sb, new DecimalFormat("000").format(i++)); 
    m.appendTail(sb);   

    System.out.println(sb); 
} 

Uscite:

001b002b003b004b005b006b007b008b 
+0

Grazie mille, molto veloce. – chandler

Problemi correlati