0

Running this code:

for(int i = 0 ; i <= 5 ; i++) {
    String id = driver.findElement(By.xpath("//[@id='selectpatientid_" + i + "']")).getText();
    System.out.println(id);
}

The output is set of strings:

vil00043
vil00032
vil00054
vil00032

How can I merge and store all these strings into a single string?

Guy
  • 46,488
  • 10
  • 44
  • 88
Sumukh
  • 21
  • 3

1 Answers1

0

First approach would be to use String.concat() as below,

 String str="";
 String id ="";
    for(int i=0;i<=5;i++){
        id = driver.findElement(By.xpath("//[@id='selectpatientid_"+i+"']")).getText();
    str.concat(id);
       }
    System.out.println(str);

But the above approach causes multiple String creations. I suggest to go for StringBuilder,

StringBuilder finalStringb =new StringBuilder();
String id ="";
        for(int i=0;i<=5;i++){
            id = driver.findElement(By.xpath("//[@id='selectpatientid_"+i+"']")).getText();
        finalStringb.append(id);
           }
        System.out.println(finalStringb);

Note--`The concat() method of String class takes the string as parameter, it appends the specified string, and returns a new String. Actually,this concat() method creates a new char array for both strings, and then put both strings into the new array, and then again creates a new String with that array.Its degrade the performance. StringBuilder works more efficent. in short if you are useing String concatenation in a loop then you can go with StringBuilder (not StringBuffer) instead of a String, because it is much faster and consumes less memory.

Zia
  • 1,001
  • 1
  • 13
  • 25
  • if you took the last paragraph from this answer word for word, you should attribute that answer, otherwise I'll have to delete this. http://stackoverflow.com/questions/4645020/when-to-use-stringbuilder-in-java/4645147#4645147 – George Stocker Jan 17 '16 at 18:16