2011-09-17 10 views
13

Mi piacerebbe sapere se c'è un equivalente a tr /// (come usato in Perl) in Java. Ad esempio, se volessi sostituire tutti "s" s con s "p" in "Mississippi" e viceversa, ho potuto, in Perl, scriverec'è un modo per usare tr /// (o equivalente) in java?

#shebang and pragmas snipped... 
my $str = "mississippi"; 
$str =~ tr/sp/ps/; # $str = "mippippissi" 
print $str; 

L'unico modo che posso pensare di farlo in Java è quello di utilizzare un personaggio fittizio con il metodo String.replace(), cioè

String str = "mississippi"; 
str = str.replace('s', '#'); // # is just a dummy character to make sure 
           // any original 's' doesn't get switched to a 'p' 
           // and back to an 's' with the next line of code 
           // str = "mi##i##ippi" 
str = str.replace('p', 's'); // str = "mi##i##issi" 
str = str.replace('#', 'p'); // str = "mippippissi" 
System.out.println(str); 

esiste un modo migliore per fare questo?

Grazie in anticipo.

+0

questo post potrebbe aiutare http://stackoverflow.com/questions/ 3254358/replace-char-to-char-in-a-string –

risposta

6

Commons 'replaceChars potrebbe essere la soluzione migliore. AFAIK non c'è sostituzione (ar ar) nel JDK.

1

A seconda di come statica che il ricambio è, si potrebbe fare

char[] tmp = new char[str.length()]; 
for(int i=0; i<str.length(); i++) { 
    char c = str.charAt(i); 
    switch(c) { 
    case 's': tmp[i] = 'p'; break; 
    case 'p': tmp[i] = 's'; break; 
    default: tmp[i] = c; break; 
    } 
} 
str = new String(tmp); 

Se le sostituzioni devono variare in fase di esecuzione, è possibile sostituire l'interruttore con una tabella di ricerca (se si sa che tutti i codepoints è necessario per sostituire la caduta in un intervallo limitato, come ASCII), o, se tutto il resto fallisce, una hashmap da Character a Character.

0

Come @ Dave già sottolineato la sostituzione più vicino è

Apache Commons StringUtils.replaceChars(String str, String searchChars, String replaceChars)

Estratto della descrizione:

... 
StringUtils.replaceChars(null, *, *)   = null 
StringUtils.replaceChars("", *, *)    = "" 
StringUtils.replaceChars("abc", null, *)  = "abc" 
StringUtils.replaceChars("abc", "", *)   = "abc" 
StringUtils.replaceChars("abc", "b", null)  = "ac" 
StringUtils.replaceChars("abc", "b", "")  = "ac" 
StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya" 
StringUtils.replaceChars("abcba", "bc", "y") = "ayya" 
StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya" 
... 
Problemi correlati