I have a string and i need to extract some value from it and put that value into another string in java

Viewed 71

I need to fetch the value of hobby i.e cricket from the string, any idea how to do that

  String str = "welcome to stackoverflow :
                  person_name : abc
                  hobby : cricket
                  Class : xyz "

i know the concept of substring but how to set the index value.Thanks in advance.

1 Answers

Given that your string has always the same format. We need to find the indexes of hobby and Class via String.indexOf(String):

String findHobbyInString(String str) {
int idxBegin = str.indexOf("hobby : ");
if (idxBegin < 0) {
  return null;
}
int idxEnd = str.indexOf("Class : ");
if (idxEnd < 0) {
  return str.substring(idxBegin + 8).trim();
}
return str.substring(idxBegin + 8, idxEnd).trim();
}

And also, because there is so much white space, I use trim() to remove this.

Related