ArtanisAce
ArtanisAce

Reputation: 957

Cannot get the correct substrings from this string

I want to get only the numbers & letters between the '@' and the ',' (or the ']') at the end; then adding them to an arraylist. Why this is not working? Doesn't see to stop in the comma...

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="";
            }
        }

Upvotes: 1

Views: 75

Answers (1)

Lukas Makor
Lukas Makor

Reputation: 2017

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

You are looping until the current char is not ',' or it is not ']'

Which basically means the loop only stops if the char is ',' and ']' at the same time, which obviously is impossible.

You should replace your "||" with "&&", such that the while loop continues as long as j is neither ',' nor ']'.


NOTE

I don´t know if this helps you, but if you know that between the '@' and the ',' there are only letters and numbers ( no special chars, because you said you just want letters and numbers) and you also know that '@' and ',' only occur 1 time you could also do something like this:

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

Upvotes: 4

Related Questions