在 java 中,如何提取所有以元音开头且长度等于 n 的单词?

javaobject oriented programmingprogramming更新于 2024/2/11 1:16:17

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

  • 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

相关文章


有用资源