Extract substring from a string

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


Solution 1:

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

Solution 2:

substring():

str.substring(startIndex, endIndex); 

Solution 3:

Here is a real world example:

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

In the example asubstring would return: h

Solution 4:

There is another way , if you want to get sub string before and after a character

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

check this post- how to find before and after sub-string in a string