要查找以元音字母开头的单词 −
String类的split()方法将给定的字符串拆分为一个字符串数组,使用String类的split()方法。
在for循环中遍历获取到的数组中的每个单词。
使用charAt()方法获取获取到的数组中每个单词的第一个字符。
立即学习“Java免费学习笔记(深入)”;
使用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
以上就是我们如何在Java中提取以元音字母开头且长度为n的所有单词?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号