1

I am trying to put strings into an array which have a space as a delimiter, it works great except for the first string has a space in front and so the first element in the array is "" instead of the first string.

    public static String[] loadMessage(String fileName)
        throws FileNotFoundException {
    String[] s = null;
    File f = new File(fileName + ".txt");
    Scanner inFile = new Scanner(f);
    while (inFile.hasNext()) {
        s = inFile.nextLine().split(" ");

    }
    inFile.close();
    return s;

}

Is there any easy solution or do I have to write another Scanner and delimiters and what not.

4 Answers4

3

Call String.trim() on each read line which removes leading and trailing spaces:

s = inFile.nextLine().trim().split(" ");

You can also use Files.readAllLines() to read all lines into a List:

for (String line : Files.readAllLines(Paths.get(fileName + ".txt",
                 StandardCharsets.UTF_8))) {
    String[] words = line.trim().split(" ");
    // do something with words
}
icza
  • 289,344
  • 42
  • 658
  • 630
2

Use the trim() method to remove leading and trailing whitespaces:

s = inFile.nextLine().trim().split(" ");

But, as @tnw pointed out, only the last line is taken into account in your code...

Joffrey
  • 13,071
  • 1
  • 42
  • 68
2

You can use trim() method before splitting.

Giancarlo Romeo
  • 567
  • 1
  • 7
  • 20
0

Also you can use regular expression. If you want to save first space, do you need something like this:

s = inFile.nextLine().split("[^s]\\s+"); 

if you are interested, you will learn more about regex here

Community
  • 1
  • 1
mkUltra
  • 2,382
  • 18
  • 38