[英]Obtain a substring that occurs multiple times?
String str="The colors are [blue], [yellow], and [green]";
我看過很多帖子如何使用正則表達式來實現這一點。
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);
我會說你想要這樣的東西,如果你嚴格不想使用正則表達式......無論出於何種原因。 正則表達式幾乎肯定會同樣快,並且代碼看起來要好得多。 但無論如何,這里有一個示例代碼,它看起來像:
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.