簡體   English   中英

如何打印每行的第一個單詞?

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

我有一個文本文件,內容如下:

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

使用String的split函數。 它根據要與字符串分割的字符返回String的數組。 您的情況如下。

 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+,您可以使用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 ,在BufferedReader分割每一行,然后獲取第二個標記並打印它

請嘗試以下代碼-:

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