获取多次出现的子字符串?

时间:2015-10-02 00:53:32

标签: java string substring

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);

1 个答案:

答案 0 :(得分:0)

如果你因为某种原因严格地不想使用正则表达式,我会说你想要这样的东西。正则表达式几乎同样快,代码看起来更好。但无论如何,这里的示例代码如何:

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);
}