如何对具有重复字符的字符串使用substring和indexOf? [英] How to use substring and indexOf for a String with repeating characters?
本文介绍了如何对具有重复字符的字符串使用substring和indexOf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下String myString="city(Denver) AND state(Colorado)";
它有重复的("和)" ...
I have the following String myString="city(Denver) AND state(Colorado)";
It has repeating "(" and ")"...
如何检索州名,即科罗拉多州.我尝试了以下方法:
How can I retrieve state name, i.e. Colorado. I tried the following:
String state = myString.substring(myString.indexOf("state(")+1,myString.indexOf(")"));
但是它给出了indexOutOfBoundException
有什么方法可以指定我需要myString中的第二个("吗?
我需要结果:String state = "Colorado";
Is there any way to specify that I need the second "(" in myString?
I need the result: String state = "Colorado";
推荐答案
使用lastIndexOf
.还增加初始偏移量,以允许子字符串state(
中的字符数:
Use lastIndexOf
. Also increase the initial offset to allow for the number of characters in the sub-string state(
:
String state = myString.substring(myString.indexOf("state(") + 6, myString.lastIndexOf(")"));
这篇关于如何对具有重复字符的字符串使用substring和indexOf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文