简体   繁体   English

如何打印每行的第一个单词?

[英]How would I print out the first word of each line?

I have a text file that reads like this: 我有一个文本文件,内容如下:

1. Bananas that are not green
2. Pudding that is not vanilla
3. Soda that is not Pepsi
4. Bread that is not stale

I just want it to print out the first word of each line NOT INCLUDING NUMBERS! 我只希望它打印出每行的第一个单词( 不包括数字)!

It should print out as: 它应打印为:

Bananas
Pudding    
Soda    
Bread

Here is my code: 这是我的代码:

public static void main(String[] args) {
    BufferedReader reader = null;
    ArrayList <String> myFileLines = new ArrayList <String>();

    try {
        String sCurrentLine;
        reader = new BufferedReader(new 
                FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
        while ((sCurrentLine = reader.readLine()) != null) {
            System.out.println(sCurrentLine);               
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.out.print(e.getMessage());
    } finally {
        try {
            if (reader != null)reader.close();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
}

Use the split function of String. 使用String的split函数。 It returns the array of the String as per the character which we want to split with the string. 它根据要与字符串分割的字符返回String的数组。 In your case, it is like as follow. 您的情况如下。

 String sCurrentLine = new String();
 reader = new BufferedReader(new 
                FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
 while ((sCurrentLine = reader.readLine() != null) {
    String words[] = sCurrentLine.split(" ");
    System.out.println(words[0]+" "+words[1]);
 } 

Java 8+ you can use the BufferedReader 's lines() method to do this very easily: Java 8+,您可以使用BufferedReaderlines()方法很容易地做到这一点:

String filename = "Your filename";
reader = new BufferedReader(new FileReader(fileName));
reader.lines()
      .map(line -> line.split("\\s+")[1])
      .forEach(System.out::println);

Output: 输出:

Bananas
Pudding
Soda
Bread

This will create a Stream of all the lines in the BufferedReader , split each line on whitespace, and then take the second token and print it 这将在BufferedReader创建所有行的Stream ,在BufferedReader分割每一行,然后获取第二个标记并打印它

Please try the code below -: 请尝试以下代码-:

outerWhileLoop: 
while ((sCurrentLine = reader.readLine()) != null) {
     //System.out.println(sCurrentLine);
     StringTokenizer st = new StringTokenizer(sCurrentLine," .");
     int cnt = 0;
     while (st.hasMoreTokens()){
        String temp = st.nextToken();
        cnt++;
        if (cnt == 2){
           System.out.println(temp);
           continue outerWhileLoop;  
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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