Home > database >  Want to separate long string and add it to list
Want to separate long string and add it to list

Time:06-08

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);

CodePudding user response:

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];
}

CodePudding user response:

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);
  • Related