如何使用 Java 從字串中提取前 n 個字元?


要查詢給定字串中的子音,請使用 charAt() 方法比較字串中每個字元和母音字母,剩下的就是子音。

示例

現場版演示

public class FindingConsonants {
   public static void main(String args[]) {

      String str = new String("Hi Welcome to Tutorialspoint");
      for(int i=0; i<str.length(); i++) {
         if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'|| str.charAt(i) == 'i' ||
            str.charAt(i) == 'o' || str.charAt(i) == 'u'|| str.charAt(i) == ' ') {
         }else{
            System.out.println("Given string contains "+str.charAt(i)+" at the index "+i);
         }
      }
   }
}

輸出

Given string contains H at the index 0
Given string contains W at the index 3
Given string contains l at the index 5
Given string contains c at the index 6
Given string contains m at the index 8
Given string contains t at the index 11
Given string contains T at the index 14
Given string contains t at the index 16
Given string contains r at the index 18
Given string contains l at the index 21
Given string contains s at the index 22
Given string contains p at the index 23
Given string contains n at the index 26
Given string contains t at the index 27

更新於: 2020-02-20

706 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.