what is the best way to extract a substring from a string in android?
you can use this code
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;
}
in this mainString
is a Super string.like
"I_AmANDROID.Devloper"
and lastString
is a string like"." and startString is like"_".
so this function
returns "AmANDROID".
enjoy your code time.:)
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
}
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
Here is a real world example:
String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1);
In the example asubstring would return: h