Home  >  Article  >  Java  >  How can we extract all words starting with a vowel and having length n in Java?

How can we extract all words starting with a vowel and having length n in Java?

WBOY
WBOYforward
2023-09-12 22:01:021339browse

How can we extract all words starting with a vowel and having length n in Java?

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.

Example

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 == &#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]);
         }
      }
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete