2014-10-01 2 views
0

내 코드에 문제가 있습니다. 다음과 같은 대부분의 경우에 'cool'을 사용합니다. Nagash는 정말 멋지다. Nagash는 정말 멋지다. 그러나 다음 중 'ish'를 취하는 것과 같은 것 : Nagash는 차갑고 Nagash는 Cooh가됩니다.처음 나타나는 문자열에서 지정된 단어를 제거하는 방법

저는 Java에 매우 익숙하며 코드는 루프와 같은 단축키 방법으로 작성되어야합니다. 답장을 보내 주시면 제 코드처럼 자바로 작성하는 방법에 대한 답변을 보내주십시오.

String deleteFromString(String word, String remove) {  
    String updated = "";  

    int count = 0; 
    int start = 0; 
    int end = 0; 

    if (stringEquals(remove, "")) { 
     updated = word; 
     return updated; 
    } 

    while (count < length(word)) { 
     if (getChar(word, count) == getChar(remove, start)) { 
      if (getChar(word, count + length(remove) - 1) == getChar(remove, length(remove) - 1)) { 
       start = count; 
       end = count + length(remove) - 1; 


       println(count); 
       println(count + length(remove) - 1); 
       count = length(word); 
      } 
     } 
     count++; 
    } 

    count = 0; 
    while (count < start - 1) { 
     updated += getChar(word, count); 
     count++; 

    } 

    while (end < length(word)) { 
     updated += getChar(word, end); 
     end++; 

    } 
    println(updated); 


    return updated;   
} 
+2

디버거를 시작하고 잘못된 결과를 생성하는 입력 데이터를 사용하여 코드를 단계별 실행하십시오. –

+0

이 코드에는 여러 테스트가 통과해야합니다. 매번 문자열과 원본에서 생략해야하는 다른 문자열을 수신합니다. – Nagash

+0

구문이 java가 아니며, 틀린 태그입니까? – user1933888

답변

0

문제는 마지막 두 개의 while 루프에 있습니다. 첫 번째 부분에서 루프는 전에 문자 대신 '제거'부분 문자열이 시작되기 전에 두 문자를 종료합니다. 두 번째 루프는 'end'문자의 위치에서 시작하므로 포함됩니다. 최종 문자의 색인은 항상 문자열의 길이보다 하나 작기 때문에 예제의 경우에는 최종 문자가 포함됩니다. 이렇게하면 삭제 된 하위 문자열 한 문자를 상위 문자열의 왼쪽으로 이동하는 효과가 나타납니다. 대신 다음을 시도하십시오.

+0

답장을 보내 주셔서 대단히 감사합니다. 나는 이것을 아침에 시험 할 것입니다. 내 코드가 어떤 경우에는 작동하지만 다른 코드에서는 작동하지 않는지 물어볼 수 있습니까? 환호 – Nagash

+0

그게 효과가! 고맙습니다. 당신의 대답으로는 효과가 없었던 유일한 시험은 제거 할 단어가 문자열에 나타나지 않았을 때였습니다. 이것은 첫 번째 문자가 카운트가 0이고 시작이 0이기 때문에 String으로 출력 할 때 놓칠 수 있도록했습니다. 주 루프 뒤의 IF를 넣어 시작과 끝 = 0을 확인합니다. '워드'. – Nagash

0

StringUtils 소스 코드를 참조 할 수 있습니다.

String test="Nagash is coolish"; 
test=test.replaceFirst("ish", ""); 
System.out.println(test); 

출력 :

Nagash is cool 

편집 : 여기 은 공단입니다


public static String replace(final String text, final String searchString, final String replacement, int max) { 
    if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { 
     return text; 
    } 
    int start = 0; 
    int end = text.indexOf(searchString, start); 
    if (end == INDEX_NOT_FOUND) { 
     return text; 
    } 
    final int replLength = searchString.length(); 
    int increase = replacement.length() - replLength; 
    increase = increase < 0 ? 0 : increase; 
    increase *= max < 0 ? 16 : max > 64 ? 64 : max; 
    final StringBuilder buf = new StringBuilder(text.length() + increase); 
    while (end != INDEX_NOT_FOUND) { 
     buf.append(text.substring(start, end)).append(replacement); 
     start = end + replLength; 
     if (--max == 0) { 
      break; 
     } 
     end = text.indexOf(searchString, start); 
    } 
    buf.append(text.substring(start)); 
    return buf.toString(); 
} 


public static boolean isEmpty(CharSequence cs) { 
    return cs == null || cs.length() == 0; 
} 
-1

간단하게하려면 이런 식으로 할 대체로 strings 번호를 처리하는 te 코드. 같은 String 작업에 대한 자세한 내용은

public class Test { 
    public static void main(String args[]) throws Exception { 
     Test test=new Test(); 
     String result=test.computeRemove("this is demo and demo", "demo", "one"); 
     // you can pass different parameters for desired result. 
     System.out.println(result); 
    } 
    public String computeRemove(String main,String remove, String replace) { 
     main=main.replaceFirst(remove,replace); 
     return main; 
    } 
} 

this 링크를 참조하시기 바랍니다.

+1

OP에 따르면 '내 코드는 루프에 작성되어야하며 단축키 방법이 필요하지 않습니다.' –

+0

@ SkaryWombat 더 좋은 방법을 보여 주면 무엇이 잘못 되었나요? –

+1

@downvoters - 다른 방법을 제시하는 것이 정확하지는 않습니다. 답변을하지 않으면 동의합니다. 그러나이 경우에는 다운 투표 (잘못된 생각)가 잘못되었습니다. – TheLostMind

관련 문제