查詢包含字串的Java檔案的首尾單詞
根據題目要求,我們需要找到給定字串的首尾單詞。
讓我們探索這篇文章,看看如何使用Java程式語言來實現。
為您展示一些示例
示例1
假設有一個字串:“Java 是一種眾所周知的、高階的、基於類的面向物件程式語言,由Sun Microsystems建立並於1995年首次釋出。目前由Oracle擁有,超過30億臺裝置執行Java。”
列印該字串的首尾單詞,即“Java”和“Oracle”。
示例2
假設有一個字串:“為了建立他們的桌面、網路和移動應用程式,所有的大公司都在積極尋求招聘Java程式設計師。”
列印該字串的首尾單詞,即“For”和“programmers”。
示例3
假設有一個字串:“我們假設讀者對程式設計環境有一定的瞭解。”
列印該字串的首尾單詞,即“we”和“environments”。
演算法
步驟1 - 建立BufferedReader類的物件。
步驟2 - 使用indexOf()方法查詢第一個空格(“ ”)的索引。然後使用substring()方法查詢第一個單詞。在substring方法中,0和第一個空格索引分別作為起始和結束索引。
步驟3 - 同樣,使用indexOf()方法查詢最後一個空格(“ ”)的索引。然後使用substring()方法查詢最後一個單詞。substring()方法(" ")+1 將給出最後一個單詞。
步驟4 - 最後,您將看到結果列印在控制檯上。
語法
為了獲得給定字串中第一個字元的索引,我們使用indexOf()方法。如果不存在,則返回-1。
以下是它的語法:
int indexOf(char ch)
其中,“ch”指的是您需要其索引位置的特定字元。
為了使用索引值從給定字串中提取子字串,我們使用String類的內建substring()方法。
以下是它的語法:
str.substring(int startIndex); str.substring(int startIndex, int endIndex);
其中,startIndex是包含的,endIndex是不包含的。
多種方法
我們提供了多種解決方案。
使用indexOf()和substring()方法
讓我們逐一檢視程式及其輸出。
方法:使用indexOf()和substring()方法
示例
在這種方法中,使用上述演算法查詢檔案中內容的首尾單詞。
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("E:\file1.txt"))) { String str; while ((str = br.readLine()) != null) { System.out.println("Content of the txt file:"); System.out.println(str); int firstSpacePosition = str.indexOf(" "); //get the first word String firstWord = str.substring(0,firstSpacePosition); //get the last word String lastWord = str.substring(str.lastIndexOf(" ")+1); //print the output of the program System.out.println("first word : "+firstWord); System.out.println("Last word: "+lastWord); } } catch (IOException e) { e.printStackTrace(); } } }
輸出
Content of the txt file: Java is a well-known high-level, class-based object-oriented programming language that Sun Microsystems created and first distributed in 1995. Over 3 billion devices run Java, which is currently owned by Oracle first word : Java Last word: Oracle
在本文中,我們探討了如何在Java中查詢包含字串的檔案的首尾單詞。