无法从此字符串中获取正确的子字符串

时间:2015-12-14 22:02:24

标签: java string char

我想只得到数字& ' @'之间的字母和',' (或者最后的']');然后将它们添加到arraylist。为什么这不起作用?没看到停在逗号中......

ArrayList<String> listUsers=new ArrayList<String>();

        String userToAdd = new String();
        String objectInText;
        objectInText="[jkasdas@8677bsd,hjkhj@554asd3]";

                for (int i=0;i<objectInText.length();i++){
            if (objectInText.charAt(i)=='@'){
                int j=i;
                while((objectInText.charAt(j)!=',') || (objectInText.charAt(j)!=']') ){
                    userToAdd+=objectInText.charAt(j+1);
                    j++;
                }


                listUsers.add(userToAdd);
                System.out.println(userToAdd);
                userToAdd="";
            }
        }

1 个答案:

答案 0 :(得分:4)

while((objectInText.charAt(j)!=',') || (objectInText.charAt(j)!=']'))

您正在循环,直到当前的char不是','或者它不是']'

这基本上意味着只有当char是','和']'时,循环才会停止,这显然是不可能的。

你应该替换你的“||”使用“&amp;&amp;”,这样只要j既不是',也不是']',while循环就会继续。


注意

我不知道这对你有帮助,但如果你知道'@'和''之间只有字母和数字(没有特殊的字符,因为你说你只想要字母和数字)和你也知道'@'和','只出现一次,你也可以这样做:

int startIndex = objectInText.indexOf('@')+1;
int endIndex = objectInText.indexOf(',');
String userToAdd =objectInText.substring(startIndex, endIndex);