如何用 Java 提取出所有以元音开头且长度等于 n 的单词?
要找出以元音字母开头的单词−
String 类的 split() 方法使用 String 类的 split() 方法将给定字符串分割成一个 Strings 数组。
在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP