查找单词以元音字母开头-
split()
String类的方法使用String类的方法将给定的字符串拆分为字符串数组split()
。
在for循环中,遍历获得的数组的每个字。
使用charAt()
方法获得所获得数组中每个单词的第一个字符。
使用if循环(如果这样)打印单词,验证字符是否等于任何元音。
假设我们有一个文本文件,其内容如下:
(cainiaojc.com) 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