what is the best way to extract a substring from a string in android?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- how to split a list into a given number of sub-lis
- Listening to outgoing sms not working android
If you know the Start and End index, you can use
If you want to get substring from specific index till end you can use :
If you want to get substring from specific character till end you can use :
If you want to get substring from after a specific character, add that number to
.indexOf(char)
:use text untold class from android:
TextUtils.substring (charsequence source, int start, int end)
substring(int startIndex, int endIndex)
Example:
String str = "abcdefgh"
str.substring(0, 4)
=> abcdstr.substring(4, 6)
=> efstr.substring(6)
=> ghThe 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 theString.substring(int, int)
method fromandroid.jar
(newest API 22), you will see:Ok, than... How do you think the private constructor
String(int, int, char[])
looks like?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:
Arrays.copyOfRange(...)
uses native array copying inside.That's it :)
Best regards!
There is another way , if you want to get sub string before and after a character
check this post- how to find before and after sub-string in a string
you can use this code
in this
mainString
is a Super string.like "I_AmANDROID.Devloper" andlastString
is a string like"." and startString is like"_". so thisfunction
returns "AmANDROID". enjoy your code time.:)