0

I'm trying to add a string to an ArrayList<String> using .add(string). This works, but it separates the variables using a comma (","). This makes it problematic for me later on when I try to split the string, because some of the sentences contain commas.

How do I change the comma to another variable when adding a string to an ArrayList?

user3776241
  • 501
  • 7
  • 19

2 Answers2

1

What you are doing is using the toString method of the ArrayList which will print each of the element of that ArrayList separated with commas.

solution:

just iterate to all of the Arraylist and append them using the String Builder.

sample:

    ArrayList<String>  s= new ArrayList<>();
    s.add("adsasd");
    s.add("adsasd");
    s.add("adsasd");
    s.add("adsasd");
    StringBuilder s2 = new StringBuilder();
    for(String s3 : s)
        s2.append(s3+" ");
    System.out.println(s2);

result:

adsasd adsasd adsasd adsasd 
Rod_Algonquin
  • 25,268
  • 6
  • 47
  • 61
0

let ArrayList str contain the list.

String myString = str.toString();
myString.replaceAll(",","something");

Also you can use String Builder.

You have a ArrayList. I suppose you are doing something with the particular index of the arrayList. So, get that index and then get the String and split it using substring by getting the index of ",". But it this method is not that convenient as your code will be long.

Somir Saikia
  • 1,512
  • 1
  • 15
  • 21