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.

3
  • 2
    The trim() method should help remove any whitespace. Commented Apr 27, 2015 at 19:49
  • 6
    I don't think this actually quite works to begin with. You're throwing out everything in the file except for the last line (unless your file only has one line anyway). Commented Apr 27, 2015 at 19:49
  • docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim() Commented Apr 27, 2015 at 19:50

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

Comments

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...

1 Comment

Yeah, I know, It would only grab one line, it's probably lazy but for now it only needs to grab one. @tnw
2

You can use trim() method before splitting.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.