2011-09-17 2 views
13

자바에서 tr /// (Perl에서 사용 된 것과 동일)가 있는지 알고 싶습니다. 예를 들어, 내가 원한다면 모든 "의"S "미시시피"의 "P"의 반대와 교체, 나는, 펄, 나는 그것을 수행하는 생각할 수거기에 자바에서 tr /// (또는 동급)을 사용하는 방법은 무엇입니까?

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

유일한 방법을 쓸 수있다 자바

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); 

이 할 수있는 더 나은 방법이 있는가 즉, String.replace() 방법 더미 문자를 사용할 수 있나요?

미리 감사드립니다.

+0

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

답변

6

커먼즈의 replaceChars이 최선의 방법 일 수 있습니다. AFAIK JDK에는 대체 (ar ar)가 없습니다.

1

교체가 얼마나 정적에 따라, 당신은 대체 런타임에 변화해야 할 경우 모든 코드 포인트는 당신이 필요로하는 것을 알고 있다면, 당신은 (테이블 조회와 스위치를 대체 할 수

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); 

할 수 ASCII와 같은 제한된 범위로 대체) 또는 다른 모든 것이 실패하면 Character에서 Character까지의 해시 맵.

0

@ 데이브는 이미 가까운 교체를 지적입니다 설명

아파치 코 몬즈 StringUtils.replaceChars(String str, String searchChars, String replaceChars)

발췌 :

... 
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" 
... 
이 게시물에 도움이 될