2013-06-20 1 views
3

내 콘솔 (아래 이미지)이 있고 newstring에 대한 모든 oldstinrg를 대체 할 명령이 있습니다. 그러나 얼마나 많은 사람들이 교체 되었는가?Java string.replace (old, new) 얼마나 많은 대체 된?

(

(코드 번만 그것이 한 것 후 B로하지만 대체 경우 두번 값이 2가 될 것이다 b에 교체 한 경우)이 코드의 단지 일부이며 하지만 다른 부분은 필요하지 않습니다 또는 어떻게 관련이 String.replaceFirst를 사용하고 스스로를 셀 수

else if(intext.startsWith("replace ")){ 


       String[] replist = original.split(" +");  

       String repfrom = replist[1]; 
       String repto = replist[2]; 

       lastorep = repfrom; 
       lasttorep = repto; 

       String outtext = output.getText(); 
       String newtext = outtext.replace(repfrom, repto); 
       output.setText(newtext); 

       int totalreplaced = 0; //how to get how many replaced strings were there? 

       message("Total replaced: " + totalreplaced + " from " + repfrom + " to " + repto); 

      } 

My console image

답변

6

코드의이 부분)에 있습니다 :

String outtext = output.getText(); 
String newtext = outtext; 
int totalreplaced = 0; 

//check if there is anything to replace 
while(!newtext.replaceFirst(repfrom, repto).equals(newtext)) { 
    newtext = newtext.replaceFirst(repfrom, repto); 
    totalreplaced++; 
} 

message("Total replaced: " + totalreplaced + " from " + repfrom + " to " + repto); 
+0

(오래된 문자열)과 (새로운 캐릭터처럼 Matcher#appendReplacementMatcher#appendTail 방법을 사용할 수 있습니다 하나 개의 반복에서 계산 얻을) 대체 할 대상은 무엇입니까? 패턴 (구)과 교체 (신품)입니까, 아니면? – donemanuel

+0

괜찮아요. 당신의 예제가 더 이상 작동하도록 수정 해주세요. –

+0

... 편집 ... 도움이 되었으면 좋겠어요. –

3

currently accepted answer에는 몇 가지 문제가 있습니다.

  1. replaceFirst을 호출 할 때마다 문자열의 처음부터 반복해야하므로 매우 효율적이지 않습니다.
  2. 그러나 더 중요한 것은 "예기치 않은"결과를 반환 할 수 있습니다. 예를 들어 "ab""a"으로 바꾸려면 문자열 "abb" 대신 1 대신 2이 반환됩니다. "abb""ab"

  3. "ab"이 일치하고 다시 교체 될 다시 일치 할 수됩니다

    • 첫 번째 반복 후 : 때문에 발생합니다. 교체 후 즉

    "ab"->"b""abb""a" 진화 할 것이다.


는 이러한 문제를 해결하고 교체는

String outtext = "Some text with word text and that will need to be " + 
     "replaced with another text x"; 
String repfrom = "text"; 
String repto = "[replaced word]"; 

Pattern p = Pattern.compile(repfrom, Pattern.LITERAL); 
Matcher m = p.matcher(outtext); 

int counter = 0; 
StringBuffer sb = new StringBuffer(); 
while (m.find()) { 
    counter++; 
    m.appendReplacement(sb, repto); 
} 
m.appendTail(sb); 

String newtext = sb.toString(); 

System.out.println(newtext); 
System.out.println(counter); 
이 코드에서 할 내가 넣어
관련 문제