首页 > 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学习者快速成长!