2012-10-27 3 views
2

그래서 특정 이유로 인해 java squawk 1.4로 제한되는 프로젝트를 진행 중입니다. 이 때문에 String 클래스에는 제목에 4 가지 방법이 포함되어 있지 않습니다. 내 프로그램에서 이러한 메서드가 필요하며 그 메서드의 기능을 자체적으로 수행하는 Util 클래스를 만들어야한다고 결론을 내렸다.isEmpty, split, contains and manually manually.

처음에는 어딘가에 존재합니까? 분명히 첫 번째 반응은 소스 코드를 String 클래스에서 복사하는 것으로 조사되었지만 이러한 메소드의 의존성은 내가 사용하기에는 너무 깊다.

둘째, split(String regex)replace(CharSequence target, CharSequence replacement)의 동작을 복제하는 데 문제가 있습니다. contains(String)isEmpty()은 쉽게 알 수 있지만 다른 것들을 코딩하는 데 문제가 있습니다.

지금 당장은 split이 작동합니다 (jdk 7과 다른 방식으로 작동하지만 버그를 얻고 싶지는 않습니다).

public static String[] split(String string, char split) { 
    String[] s = new String[0]; 
    int count = 0; 
    for (int x = 0; x < string.length(); x++) { 
     if (string.charAt(x) == split) { 
      String[] tmp = s; 
      s = new String[++count]; 
      System.arraycopy(tmp, 0, s, 0, tmp.length); 
      s[count - 1] = string.substring(x).substring(1); 
      if (contains(s[count - 1], split + "")) { 
       s[count - 1] = s[count - 1].substring(0, s[count - 1].indexOf(split)); 
      } 
     } 
    } 
    return s.length == 0 ? new String[]{string} : s; 
} 

Replace 나는 훨씬 더 힘들며 지금 몇 시간 씩 노력해 왔습니다. 이것은 Google/아카이브가 결코 모험을 시도한 적이없는 질문 인 것 같습니다.

방법 제작
+0

'사항 String.split (문자열 정규식)'당신은 당신이 그것을 구현할 필요가 확신 ... 자바 1.4에 존재? (나는 Squawk에 대해서는 아무 것도 모른다.) –

+0

@JonSkeet 네, sun squawk라는 것을 사용하고 있는데 String 클래스에는 존재하지 않습니다. –

+0

* 사용할 수있는 *에 대한 참조를 제공 할 수 있습니까? 단순히 JDK 버전과 일치하지 않는 경우 대체 구현을 제공하는 것이 더 어려울 것입니다 ... –

답변

0

이 ...

public static boolean isEmpty(String string) { 
    return string.length() == 0; 
} 

public static String[] split(String string, char split) { 
    return _split(new String[0], string, split); 
} 

private static String[] _split(String[] current, String string, char split) { 
    if (isEmpty(string)) { 
     return current; 
    } 
    String[] tmp = current; 
    current = new String[tmp.length + 1]; 
    System.arraycopy(tmp, 0, current, 0, tmp.length); 
    if (contains(string, split + "")) { 
     current[current.length - 1] = string.substring(0, string.indexOf(split)); 
     string = string.substring(string.indexOf(split) + 1); 
    } else { 
     current[current.length - 1] = string; 
     string = ""; 
    } 
    return _split(current, string, split); 
} 

public static boolean contains(String string, String contains) { 
    return string.indexOf(contains) > -1; 
} 

public static String replace(String string, char replace, String replacement) { 
    String[] s = split(string, replace); 

    String tmp = ""; 
    for (int x = 0; x < s.length; x++) { 
     if (contains(s[x], replace + "")) { 
      tmp += s[x].substring(1); 
     } else { 
      tmp += s[x]; 
     } 
    } 
    return tmp; 
}