JCCS
JCCS

Reputation: 611

Reading from a text file and ignoring spaces

I am reading from a text file that looks like this:

A B C D
E F G H
I J K L
M N O P

I will be storing this into a 4x4 char array. My problem is that whenever I am reading from the file it counts the space in between the letters causing it to store the space in the char array. How can i read the line without the spaces? Here is what i have got:

char[][] letters = new char[4][4]
Scanner read = new Scanner(new File("letters.txt"));
while(read.hasNextLine()) {
    for(int row = 0; row < letters.length; row++) {
        String line = read.nextLine();
        for(int col = 0; col < letters[row].length; col++) {
            letters[row][col] = line.charAt(col);
        }
    }
}

Upvotes: 0

Views: 8344

Answers (4)

Francisco Romero
Francisco Romero

Reputation: 13199

You can use split function. It will provide to you to store each line of your file in an array taking as reference the space " ". Also, you should declare your line variable out of the loop.

For example, if you have your first line: A B C D

line = read.nextLine(); //Here you read the line

/* Here you store each character of your line in a position of the array 
  because you are taking as reference the space " " */

array = line.split(" "); 

System.out.println(array[0]); //A
System.out.println(array[1]); //B
System.out.println(array[2]); //C
System.out.println(array[3]); //D

Your code have to look like:

char[][] letters = new char[4][4];
String line;
char ch; 
String[] array;
Scanner read = new Scanner(new File("letters.txt"));
while(read.hasNextLine()) {
    for(int row = 0; row < letters.length; row++) {
        line = read.nextLine();
        array = line.split(" ");

        for(int col = 0; col < letters[row].length; col++) {
        {
           ch = array[col].charAt(0);
           letters[row][col] = ch;
        }

    }
}

Upvotes: 0

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

You could just use the replace method that works

for(int row = 0; row < letters.length; row++) {
    String line = read.nextLine();
    line = line.replace(" ", "");
    for(int col = 0; col < letters[row].length; col++) {
        letters[row][col] = line.charAt(col);
    }
}

This will take your initial String and basically remove all the spaces.

This is your input for example :

A B C D

And here is the output of line.replace(" ", "")

ABCD

Upvotes: 1

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22234

If you only want to get single chars from line then use

letters[row][col] = line.charAt(2*col);

and it will just skip the spaces

Upvotes: 3

andrewdleach
andrewdleach

Reputation: 2466

Split your string obtained from readLine () on the " " pattern

Upvotes: 0

Related Questions