如何用 Java 提取出所有以母音開頭且長度等於 n 的單詞?
要找出以母音字母開頭的單詞−
String 類的 split() 方法使用 String 類的 split() 方法將給定字串分割成一個 Strings 陣列。
在 for 迴圈中遍歷獲得的陣列的每個單詞。
使用 charAt() 方法獲取獲得的陣列中每個單詞的第一個字元。
使用 if 迴圈驗證該字元是否等於任何母音,如果是,則列印該單詞。
示例
假設我們有一個包含以下內容的文字檔案−
Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
以下 Java 程式打印出該檔案中所有以母音字母開頭的單詞。
import java.io.File;
import java.util.Scanner;
public class WordsStartWithVowel {
public static String fileToString(String filePath) throws Exception {
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
String input = new String();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input);
}
return sb.toString();
}
public static void main(String args[]) throws Exception {
String str = fileToString("D:\sample.txt");
String words[] = str.split(" ");
for(int i = 0; i < words.length; i++) {
char ch = words[i].charAt(0);
if(ch == 'a'|| ch == 'e'|| ch == 'i' ||ch == 'o' ||ch == 'u'||ch == ' ') {
System.out.println(words[i]);
}
}
}
}輸出
originated idea exists a of on-line and at own of
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP