首页 > 文章列表 > 我们如何在Java中提取以元音字母开头且长度为n的所有单词?

我们如何在Java中提取以元音字母开头且长度为n的所有单词?

java 提取 长度 单词 元音字母
462 2023-09-08

要查找以元音字母开头的单词 −

  • 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 == '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