首頁 > Java > java教程 > 主體

我們如何在Java中提取以元音字母開頭且長度為n的所有單字?

WBOY
發布: 2023-09-12 22:01:02
轉載
1366 人瀏覽過

我們如何在Java中提取以元音字母開頭且長度為n的所有單字?

要尋找以母音字母開頭的單字−

  • String類別的split()方法將給定的字串拆分為一個字串數組,使用String類別的split()方法。

  • 在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 == &#39;a&#39;|| ch == &#39;e&#39;|| ch == &#39;i&#39; ||ch == &#39;o&#39; ||ch == &#39;u&#39;||ch == &#39; &#39;) {
            System.out.println(words[i]);
         }
      }
   }
}
登入後複製

輸出

originated
idea
exists
a
of
on-line
and
at
own
of
登入後複製

以上是我們如何在Java中提取以元音字母開頭且長度為n的所有單字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!