Program Tip

문자열에서 부분 문자열 추출

programtip 2020. 11. 12. 20:07
반응형

문자열에서 부분 문자열 추출


안드로이드의 문자열에서 부분 문자열을 추출하는 가장 좋은 방법은 무엇입니까?


시작 및 종료 색인을 알고 있으면 다음을 사용할 수 있습니다.

String substr=mysourcestring.substring(startIndex,endIndex);

끝까지 특정 색인에서 하위 문자열을 얻으려면 다음을 사용할 수 있습니다.

String substr=mysourcestring.substring(startIndex);

특정 문자에서 끝까지 하위 문자열을 얻으려면 다음을 사용할 수 있습니다.

String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue"));

특정 문자 뒤에서 하위 문자열을 얻으려면 해당 숫자를 .indexOf(char)다음에 추가하십시오 .

String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue") + 1);

substring():

str.substring(startIndex, endIndex); 

다음은 실제 사례입니다.

String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1); 

예제에서 asubstring 은 다음을 반환합니다. h


문자 앞뒤에 하위 문자열을 얻으려면 다른 방법이 있습니다.

String s ="123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];

이 게시물을 확인하십시오 -문자열에서 하위 문자열 전후를 찾는 방법


substring(int startIndex, int endIndex)

endIndex를 지정하지 않으면 메서드는 startIndex의 모든 문자를 반환합니다 .

startIndex : 시작 색인이 포함됩니다.

endIndex : 끝 색인이 배타적 임

예:

String str = "abcdefgh"

str.substring(0, 4) => abcd

str.substring(4, 6) => ef

str.substring(6) => gh


android에서 텍스트 공개 클래스 사용 :
TextUtils.substring (charsequence source, int start, int end)


subSequence를 사용할 수 있으며 C의 substr과 동일합니다.

 Str.subSequence(int Start , int End)

이 코드를 사용할 수 있습니다

    public static String getSubString(String mainString, String lastString, String startString) {
    String endString = "";
    int endIndex = mainString.indexOf(lastString);
    int startIndex = mainString.indexOf(startString);
    Log.d("message", "" + mainString.substring(startIndex, endIndex));
    endString = mainString.substring(startIndex, endIndex);
    return endString;
}

이것은 mainStringSuper string.like "I_AmANDROID.Devloper"이고 lastString문자열입니다. " startString은 "_"와 같습니다. 그래서 이것은 function"AmANDROID"를 반환합니다. 코드 시간을 즐기십시오. :)


Android에서 하위 문자열을 얻는 가장 좋은 방법은 @ user2503849가 말했듯이 TextUtlis.substring(CharSequence, int, int)방법을 사용하는 것입니다. 이유를 설명 할 수 있습니다. (최신 API 22) String.substring(int, int)메서드를 살펴보면 android.jar다음이 표시됩니다.

public String substring(int start) {
    if (start == 0) {
        return this;
    }
    if (start >= 0 && start <= count) {
        return new String(offset + start, count - start, value);
    }
    throw indexAndLength(start);
}

좋아요,보다 ... 개인 생성자 String(int, int, char[])어떻게 생겼을까 요?

String(int offset, int charCount, char[] chars) {
    this.value = chars;
    this.offset = offset;
    this.count = charCount;
}

As we can see it keeps reference to the "old" value char[] array. So, the GC can not free it.

In the newest Java it was fixed:

String(int offset, int charCount, char[] chars) {
    this.value = Arrays.copyOfRange(chars, offset, offset + charCount);
    this.offset = offset;
    this.count = charCount;
}

Arrays.copyOfRange(...) uses native array copying inside.

That's it :)

Best regards!


When finding multiple occurrences of a substring matching a pattern

    String input_string = "foo/adsfasdf/adf/bar/erqwer/";
    String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input_string);

    while(matcher.find()) {
      String str_matched = input_string.substring(matcher.start(), matcher.end());
        // Do something with a match found
    }

참고URL : https://stackoverflow.com/questions/5414657/extract-substring-from-a-string

반응형