Extract substring from a string

后端 未结 10 1892
栀梦
栀梦 2020-12-02 19:55

what is the best way to extract a substring from a string in android?

相关标签:
10条回答
  • 2020-12-02 20:03

    The best way to get substring in Android is using (as @user2503849 said) TextUtlis.substring(CharSequence, int, int) method. I can explain why. If you will take a look at the String.substring(int, int) method from android.jar (newest API 22), you will see:

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

    Ok, than... How do you think the private constructor String(int, int, char[]) looks like?

    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!

    0 讨论(0)
  • 2020-12-02 20:06

    substring(int startIndex, int endIndex)

    If you don't specify endIndex, the method will return all the characters from startIndex.

    startIndex : starting index is inclusive

    endIndex : ending index is exclusive

    Example:

    String str = "abcdefgh"

    str.substring(0, 4) => abcd

    str.substring(4, 6) => ef

    str.substring(6) => gh

    0 讨论(0)
  • 2020-12-02 20:11

    If you know the Start and End index, you can use

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

    If you want to get substring from specific index till end you can use :

    String substr=mysourcestring.substring(startIndex);
    

    If you want to get substring from specific character till end you can use :

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

    If you want to get substring from after a specific character, add that number to .indexOf(char):

    String substr=mysourcestring.substring(mysourcestring.indexOf("characterValue") + 1);
    
    0 讨论(0)
  • 2020-12-02 20:14

    You can use subSequence , it's same as substr in C

     Str.subSequence(int Start , int End)
    
    0 讨论(0)
  • 2020-12-02 20:16

    use text untold class from android:
    TextUtils.substring (charsequence source, int start, int end)

    0 讨论(0)
  • 2020-12-02 20:18

    substring():

    str.substring(startIndex, endIndex); 
    
    0 讨论(0)
提交回复
热议问题