To find words starting with vowels −
The split() method of String class splits the given string into An array of strings, using the split() method of the String class.
Traverse each word in the obtained array in the for loop.
Use the charAt() method to get the first character of each word in the obtained array.
Use an if loop to verify if the character is equal to any vowel, and if so, print the word.
Suppose we have a text file containing the following −
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.
The following Java program prints the characters in this file that begin with a vowel All words.
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
The above is the detailed content of How can we extract all words starting with a vowel and having length n in Java?. For more information, please follow other related articles on the PHP Chinese website!