[英]Obtain a substring that occurs multiple times?
String str="The colors are [blue], [yellow], and [green]";
I have seen many posts how to achieve this using regex.我看过很多帖子如何使用正则表达式来实现这一点。
Here is my for loop that keeps giving me a string out of range error:
for (int i=0;i<str.length();i++){
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
System.out.println(result);
I would say you want something like that if you strictely don't want to use regex... for whatever reason.我会说你想要这样的东西,如果你严格不想使用正则表达式......无论出于何种原因。 Regex will almost certainely be equally fast and the code looks much much nicer.
正则表达式几乎肯定会同样快,并且代码看起来要好得多。 But anyway here's a sample code how it would look like:
但无论如何,这里有一个示例代码,它看起来像:
String str="The colors are [blue], [yellow], and [green]";
ArrayList<String> arr = new ArrayList<String>();
for(int i = str.indexOf('[', 0); i != -1; i = str.indexOf('[', i + 1)) {
arr.add(str.substring(i + 1, str.indexOf(']', i)));
}
for(String s : arr) {
System.out.println(s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.