Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

substring with nth occurrence in java

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...