簡體   English   中英

計算 java 中字符串中的元音

[英]count vowels in a string in java

我想計算字符串中每個單詞的元音並打印每個單詞的元音數。 我只知道如何計算字符串中的所有元音,我試過了。 但我想要每個單詞的元音計數。 我怎樣才能打印出來?

String s="hai hello";
    int count=0;
    for(int i=0;i<s.length();i++)
    {
        if(s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u')
            count++;
    }
    System.out.println(count);

如果輸入是“hai hello”,那么預期的 output將為“1 2”。

我試圖解決你的問題

        String string = "hai hello";
        String[] wordAr = string.split(" ");
        int count = 0;
        for (String s : wordAr) {
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') {
                    count++;
                }
            }
            System.out.print(count + "\t");
            count = 0;
        }

您可以為此使用正則表達式...

String string = "hai hello";
String[] wordAr = string.split(" ");
for (String s : wordAr) {
    System.out.println(s.replaceAll("(?i)[^aeiouy]", "").length());
}

(?i)將使字符不區分大小寫

您可以在循環中使用condition:

if (s.charAt(i) == ' ' ) {
  system.out.println(count)
  count = 0;
}

每次看到空白時,它將打印並設置為零。

您可以使用

String result = Arrays.asList(string.split(" ")).stream().map(s -> countVowel(s))
        .collect(Collectors.joining(" "));

其中countVowel返回字符串中的元音的nr(請參見“ pantha istiaque”答案)以獲取整個結果

public static Map<String, Integer> countVowelsByWords(String str) {
    Map<String, Integer> map = new HashMap<>();

    Arrays.stream(str.toLowerCase().split("[^a-z]+"))
          .distinct()
          .forEach(word -> {
              int count = 0;

              for (int i = 0; i < word.length(); i++) {
                  char ch = word.charAt(i);

                  if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                      count++;
              }

              map.put(word, count);
          });

    return map;
}

您可以嘗試以下代碼:

import java.util.ArrayList;
import java.util.List;

public class Sam {
public static void main(String... args) {
    String str="hai hello";
    List<Integer> list=new ArrayList<>();
    String[] s=str.split(" ");
    for(int i=0;i<s.length;i++) {
         list.add(a(s[i])); 
    }
    System.out.println(list); //output : [2,2]      
}

static int a(String s) {
    int cou=0;
    for(int i=0;i<s.length();i++) {
        if(s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u') {
            cou++;
        }
    }
    return cou;
 }
}

只是為了展示另一個簡單的概念...使用帶有正則表達式 (RegEx)的String#replaceAll()方法來計算單詞或字符串中的元音數量。

正則表達式( "(?i)[^aeiou]"的內使用字符串#的replaceAll()方法基本上告訴替換的所有字符的方法與空字符串( “”),其是未A,E,I,O,u( 無論大小寫)。 然后,我們將剩余的字符數(全部為元音)作為單詞或字符串中元音數量的計數,因為它們是唯一替換的字符:

String a = "This sentence has vowels";
int vowelCount = 0;
String[] words = a.split("\\s+");
for (int i = 0; i < words.length; i++) {
    vowelCount = words[i].replaceAll("(?i)[^aeiou]", "").length();
    System.out.println("Word #" + (i + 1) + " [" + words[i] + 
                       "] contains " + vowelCount + " vowels.");
}

控制台輸出將如下所示:

Word #1 [This] contains 1 vowels.
Word #2 [sentence] contains 3 vowels.
Word #3 [has] contains 1 vowels.
Word #4 [vowels] contains 2 vowels.

您可以使用 java 8 計算元音:

  String str="a quick brown fox jumps over a lazy dog";
  List<Character> vowels=Arrays.asList('a', 'e', 'i', 'o', 'u');
  Long vowelCount = str.chars().filter(c -> vowels.contains((char) c)).count();
String str="hello";
long count = str.chars().filter((x) -> {
        return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');
}).count();
System.out.println("count:::: "+count);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM