Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เราจะแยกคำทั้งหมดที่ขึ้นต้นด้วยสระและความยาวเท่ากับ n ใน java ได้อย่างไร


การหาคำที่ขึ้นต้นด้วยตัวอักษรสระ -

  • วิธี split() ของคลาส String แยกสตริงที่กำหนดเป็นอาร์เรย์ของ Strings โดยใช้วิธี split() ของคลาส String

  • ใน for วนซ้ำผ่านแต่ละคำของอาร์เรย์ที่ได้รับ

  • รับอักขระตัวแรกของแต่ละคำในอาร์เรย์ที่ได้รับโดยใช้เมธอด charAt()

  • ตรวจสอบว่าอักขระเท่ากับสระใด ๆ โดยใช้ if loop หากพิมพ์คำนั้น

ตัวอย่าง

สมมติว่าเรามีไฟล์ข้อความที่มีเนื้อหาดังต่อไปนี้ -

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