[英]Display only one kind of the vowel
我只需要顯示一種從字符串中檢查的元音類型,但它會一直顯示重復的元音。
輸入:我整天都在你身邊,並且知道你。
輸出:
元音:我是輔音:mnyldwthcr
這意味着它將顯示句子中使用的元音。 輔音也一樣
import java.util.Scanner;
public class aaaa {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.println ("Enter a string:");
String s = input.nextLine();
char[] sChars = s.toCharArray();
char[] vowels = {'a','e','i','o','u','A','E','I','O','U'};
char[] consonant = {'b','c','d','f','g','h','k','j','l','m','n','p','q','r','s','t','x','v','w','y','z'};
for (int j = 0 ; j < sChars.length ; j++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( sChars[j] == vowels[i]) {
System.out.print(vowels[i]+ " ");
}
}
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
for(int n = 0; n < consonant.length ; n++){
if ( sChars[m] == consonant[n]){
System.out.print(consonant[n]+" ");
}
}
}
}
}
嘗試這個:
System.out.println("Vowels: " + s.toLowerCase().replaceAll("[^aeiou]|(.)(?=.*\\1)", "")
+ "\nConsonants: " + s.toLowerCase().replaceAll("[aeiou]|(.)(?=.*\\1)", ""));
通過使用正則表達式選擇要刪除的感興趣字符,這可以在一行中完成整個作業。
僅供參考,正則表達式[aeiou]|(.)(?=.*\\1)
表示“任何元音,或任何不再出現的字符”。 交替的第一場比賽在那里停止,這就是為什么我不需要為右手邊的輔音編碼字符類 - 點只會匹配非元音。
類似的方法用於打印元音,除了它是否定的字符類。
有更有效的方法可以做到這一點,但我會嘗試盡可能少地改變你的解決方案。
跟蹤已打印的字母,不要再次打印:
char[] vowels = {'A','E','I','O','U'};
char[] consonant = {'B','C','D','F','G','H','K','J','L','M','N','P','Q','R','S','T','X','V','W','Y','Z'};
// create a collection to store the letters already used
List<Character> lettersUsed = new ArrayList<Character>();
for (int j = 0 ; j < sChars.length ; j++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( Character.toUpperCase(sChars[j]) == vowels[i]) {
// if the collection of used letters does not contain this one
if(!lettersUsed.contains(Character.toUpperCase(sChars[j]))) {
System.out.print(sChars[j]+ " ");
// add this letter to the collection of letters used
lettersUsed.add(Character.toUpperCase(sChars[j]));
}
// now that you've found a match, break out of the inner loop
break;
}
}
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
for(int n = 0; n < consonant.length ; n++){
if ( Character.toUpperCase(sChars[m]) == consonant[n]){
// if the collection of used letters does not contain this one
if(!lettersUsed.contains(Character.toUpperCase(sChars[m]))) {
System.out.print(sChars[m]+" ");
// add this letter to the collection of letters used
lettersUsed.add(Character.toUpperCase(sChars[m]));
}
// now that you've found a match, break out of the inner loop
break;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.