简体   繁体   中英

Grab Words from .txt file - Java

I have been tasked to grab 100 words, at random, from a dictionary.txt file. I have been able to read to the file using a scanner, populate an array based on each new line (which would separate the words + definitions to a single element each) and then formatted it to remove the brackets. However, now I need to figure out how to grab just the first word from each array element, possibly by using a regex or the fact that it is the first word in each element being ended by a space.

My question is how would one go about grabbing just the first word out of every array element, or, as mentioned below, grab the first word per line.

You probably just want to use yourString.split(" ")[0] .

However, I believe constructing an array of all the lines is wasteful. You could instead construct an array of the first words of the file using a Scanner, or you could even do a first parse to count the number of lines and then only construct the final desired result.

Oh and a last edit for your regex culture : the appropriate regex would have been ^\\S+ which grabs all non-space characters at the start of a string. It's most probably less efficient than using String.split() .

The easiest way to grab the first word from each line would be by using indexOf() and substring() :

String[] lines = new String[100];
String[] words = new String[100];
int x;

//your code for getting the lines of text from the file goes here

for (int i=0; i<lines.length; i++) {
    x = lines[i].indexOf(" ");
    words[i] = lines[i].substring(0, x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM