【问题标题】:How would I print out the first word of each line?我将如何打印出每行的第一个单词?
【发布时间】:2018-12-02 04:04:15
【问题描述】:

我有一个这样的文本文件:

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

我只是想让它打印出每行的第一个单词 不包括数字!

它应该打印为:

Bananas
Pudding    
Soda    
Bread

这是我的代码:

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();
        }
    }
}

【问题讨论】:

标签: java string arraylist bufferedreader


【解决方案1】:

使用String的split函数。它根据我们要与字符串拆分的字符返回字符串的数组。在您的情况下,如下所示。

 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]);
 } 

【讨论】:

  • 实际上您只想打印单词[1],因为不应打印数字。
【解决方案2】:

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);

输出:

Bananas
Pudding
Soda
Bread

这将在BufferedReader 中的所有行中创建一个Stream,在空白处分割每一行,然后获取第二个标记并打印它

【讨论】:

    【解决方案3】:

    请试试下面的代码-:

    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;  
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 2019-12-03
      相关资源
      最近更新 更多