Parse String with delimiter symbol into Array

65,803

Solution 1

Yes use String.split() for each line as you read it from the file.

line.split("\\|");

Solution 2

An alternative is to use String.split(...)

String s="Hi farshad zeinali/ how are you?/i have a question!/can you help me?";
String[] ss=s.split("/");
for(int i=0;i<ss.length;i++)
{
    System.out.println(ss[i]);
}
Share:
65,803
gaussd
Author by

gaussd

Im a Computer Science Student in Freiburg (Germany).

Updated on November 03, 2020

Comments

  • gaussd
    gaussd over 3 years

    I have a file containing lines of this type:

    "Andorra la Vella|ad|Andorra la Vella|20430|42.51|1.51"

    I basically just want to have a String Array containing the entries between the | delimiter:

    ["Andorra la Vella", "ad", "Andorra la Vella", "20430", "42.51", "1.51"]

    Can this be done with regular expressions?

  • chiranjeevigk
    chiranjeevigk about 9 years
    But @pangea can you explain why we need to add that "\\"?
  • Oliver Hausler
    Oliver Hausler over 8 years
    @chiranjeevibmse You probably found out already: The | needs to be escaped because split expects a regex value, not a string, and | is a reserved character in regex. regular-expressions.info/characters.html