I want to implement a program that reads a file (i.e. .txt) and saves the file in an array (I have done this). Then I want to have a 2-dimensional array where I save only the words for every line.
For example if the file contains two lines with two words in every line I want in array[0][0] the first word of the first line and in array[0][1] to have the second word of the first line, etc.
I have the following code:
for (int i=0; i < aryLines.length; i++) {
String[] channels = aryLines[i].split(" ");
System.out.println("line " + (i+1) + ": ");
for (int j=0; j < channels.length; j++){
System.out.println("word " + (j+1) + ": ");
System.out.println(channels[j]);
}
System.out.println();
}
where the aryLines contatins all the lines but I didn’t find a solution that performs what I described.
Let your
1-Darray is: –You first need to declare an array of array: –
Then iterate over it, and for each line, split it and assign it to inner array: –
Now, the problem will be, not all words are separated by just
space. They also have many punctuation that you need to consider. I would leave it to you to split it on all the punctuation.For e.g.: –
Now, you would need to find all the punctuation used in your sentence.
One thing which you can do is use a
Regexto match a pattern for words only, if you are not sure about what allpunctuationare used in your line. And add each matched word to an arraylist.Let’s see it working in the above example: –
OUTPUT : –
You can use this approach in your above loop that I posted.