0

I have a long string essentially like below, I want to add each line in the string into the List as its own individual string. In this case for each line, there would be 3 different elements in the List.

 String content = "das,fdfd,fdsd,dsds,arer" + "\n" +
                     "abv,dsds,dsa,wew,ewewew" + "\n" +
                     "dfdf,wewes,mds,ojop,nsmcd"

while (content.contains("\n")){
     list = Arrays.asList(content.split("\n"));
    }

   System.out.println(list);
Ajm Kir
  • 17
  • 4

2 Answers2

1

I think you already have the answer? Maybe this could make it more clear. Split Java String by New Line

String content = "das,fdfd,fdsd,dsds,arer" + "\n" +
                     "abv,dsds,dsa,wew,ewewew" + "\n" +
                     "dfdf,wewes,mds,ojop,nsmcd";
if (content.contains("\n")) {
    String[] parts = content.split("\\r?\\n");
    String part1 = parts[0]; 
    String part2 = parts[1];
    String part3 = parts[2];
}
ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18
1

You don't need to have a while loop, the split(String regex) already returns String[]. The \ character should also be escaped, so "\n" becomes "\\n".

String content = "das,fdfd,fdsd,dsds,arer" + "\n" +
            "abv,dsds,dsa,wew,ewewew" + "\n" +
            "dfdf,wewes,mds,ojop,nsmcd";

List<String> list = Arrays.asList(content.split("\\n"));
System.out.println(list);

See this code run live at Ideone.com.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
happy songs
  • 835
  • 8
  • 21