Reputation: 55
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.
Upvotes: 1
Views: 2558
Reputation: 3068
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
Upvotes: 0
Reputation: 417777
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
}
Upvotes: 3
Reputation: 37720
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...
Upvotes: 2