Lazar Kukolj
Lazar Kukolj

Reputation: 706

trim String and add to ArrayList

the variable TEST is equal to this

[email protected]_Hd_s [email protected]_Update_on the [email protected]_Ksks_ajsj 

i want to pull each "product" out so i have an ArrayList equal to this

[email protected]_Hd_s
[email protected]_Update_on
[email protected]_Ksks_ajsj

Right now the only thing in my array list is [email protected]_Hd_s

How can i pull each "product" from the one variable (TEST) in a loop and add it to the ArrayList?

My code so far:

String TEST = result;

ArrayList<String> Products = new ArrayList<>();
boolean flag = true;

    while(flag == true){
      Products.add(TEST.substring(0, TEST.indexOf(' ')));
      TEST = TEST.substring(TEST.indexOf(' ') + 1);

          if(TEST.equals("")){
               flag = false;
          }else{
               TEST = TEST.substring(1);
           }
    }

see

Upvotes: 0

Views: 483

Answers (3)

Chris Gong
Chris Gong

Reputation: 8229

Your one step away from doing it. After the first iteration of your while loop, you do retrieve [email protected]_Hd_s, but after that the loop runs infinitely because the other parts of the string are not being accessed. The solution is to cut out the part you retrieved from the string each time you add it to Products. I should also note that this will only work if TEST ends with a space " ". Here is a way to approach this.

String TEST = result;

ArrayList<String> Products = new ArrayList<>();
boolean flag = true;

while(flag == true){
  Products.add(TEST.substring(0,TEST.indexOf(' ')));
  TEST = TEST.substring(TEST.indexOf(' '));//cutting the last email added from the string
    if(TEST.equals(" ")){
       flag = false;
    }
    else{
       TEST = TEST.substring(1); //remove that space so that it doesn't get  
                                 //counted again in the next iteration
    }

}

Upvotes: 1

marcellorvalle
marcellorvalle

Reputation: 1679

An alternative one line solution using String.split() function:

List<String> products = Arrays.asList(TEST.split(" "));

Upvotes: 0

Nguyen Quang Anh
Nguyen Quang Anh

Reputation: 315

Seeing your input string doesn't simply have email separated by white space, I suggest you use Pattern and Matcher. First you need to define the email's pattern (you can google it), then use the example in this : http://www.tutorialspoint.com/java/java_regular_expressions.htm

Upvotes: 0

Related Questions