Reputation: 638
I have string 1-12.32;2-100.00;3-82.32; From this I need to extract the numbers based on my passing position value. If I pass 3, I would need 82.32, similarly if I pass 2, i need 100.00. I build a function as like below but it is not working as expected. Could someone correct this/help on this?
function String res(String str, String pos){
String res=str.substring(str.indexOf(pos+"-")+2, str.indexOf(";",str.indexOf(pos)));
return res;
}
where str= 1-12.32;2-100.00;3-82.32; pos=1 (or) 2 (or) 3
Upvotes: 1
Views: 101
Reputation: 393791
Your end index is incorrect. You should search for the index of the first ";" after the start index.
int begin = str.indexOf(pos+"-") + 2;
String res=str.substring(begin, str.indexOf(";",begin));
str.indexOf(";",str.indexOf(pos))
will give you the index of the first ";", since str.indexOf(pos)
gives you the index of the first "2", which is the first "2" in "1-12.32;".
Upvotes: 3