Java 如何检测程序中的元音和辅音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20208970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:19:03  来源:igfitidea点击:

How to Detect the Vowels and Consonants in my program

java

提问by user3020412

    String text;
    System.out.print ("Enter a String:");
    text = console.nextLine();

    int spaces = 0;
    int consonants = 0;
    int vowelcount = 0 ;

    for (int index = 0; index < text.length(); index++) {
    char letters = text.charAt(index);


    if (letters == 'A' || letters == 'a')
        vowelcount++;



    else if (letters != 'a' && letters != 'e' && letters != 'i' && letters != 'o' && letters != 'u')
        consonants++;

    }


        System.out.println ("Vowels:" + vowelcount  + "\nConsonants :" + consonants + "\nSpaces : " + spaces);

Sample OutputString: Hannah Last Portion of OutputVowels Detected: a a Consonants Detected: h n n h

示例输出字符串:Hannah 检测到的输出元音的最后一部分:aa 检测到的辅音:hnnh

回答by Bohemian

Just use regex, and it only takes you one line count:

只需使用正则表达式,它只需要你一行数:

int spaces = text.replaceAll("\S", "").length();
int consonants = text.replaceAll("(?i)[\saeiou]", "").length();
int vowelcount = text.replaceAll("(?i)[^aeiou]", "").length();

These all replace chars notmatching the target character type with a blank - effectively deleting them - then using String.length() to give you the count.

这些都将与目标字符类型匹配的字符替换为空白 - 有效地删除它们 - 然后使用 String.length() 为您提供计数。

回答by NP83

You could use a regex ex:

您可以使用正则表达式:

  • White spaces: (?\s+)
  • Vowels: (?[aeijo]+)
  • 空格:(?\s+)
  • 元音:(?[aeijo]+)

I guess the next one should be easy ;)

我想下一个应该很容易;)

Then use the group match functionality and count all instances

然后使用组匹配功能并计算所有实例

(I most times use a regex tool while building the regex e.g. http://gskinner.com/RegExr/)

(我大多数时候在构建正则表达式时使用正则表达式工具,例如http://gskinner.com/RegExr/

回答by Paul Samsotha

Here are a couple help methods

这里有几个帮助方法

public static boolean isVowel(char c){
    String vowels = "aeiouAEIOU";
    return vowels.contains(c);
}

public static boolean isConsanant(char c){
    String cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return cons.contains(c);
}

Use them here

在这里使用它们

char c = line.charAt(i);
int vowelCount = 0;
int consanantCount = 0;
int space = 0;
int punctuation = 0;

if (isVowel(c))
    vowelCount++;
else if (isConsanant(c))
    consanantCount++;
else if (Character.isWhitepace(c))
    space++;
else
    punctuation++;

回答by Developer Marius ?il?nas

To detect vowels and consonants you need an array for CONSONANTS chars and then check if a char is in this array. Here you can see a working example, it counts consonants, vowels and spaces: import java.io.Console;

要检测元音和辅音,您需要一个用于 CONSONANTS 字符的数组,然后检查该数组中是否有一个字符。在这里你可以看到一个工作示例,它计算辅音、元音和空格: import java.io.Console;

public class Vowels
{
    public static final char[] CONSONANTS =
    {
        'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
    };

    public static final char SPACE = ' ';

    public static char[] getConsonants()
    {
        return CONSONANTS;
    }

    public static boolean isConsonant(char c)
    {
        boolean isConsonant = false;
        for (int i = 0; i < getConsonants().length; i++)
        {
            if (getConsonants()[i] == c)
            {
                isConsonant = true;
                break;
            }
        }
        return isConsonant;
    }

    public static boolean isSpace(char c)
    {
        return SPACE == c;
    }

    public static void main(String[] args)
    {
        int spaces     = 0;
        int consonants = 0;
        int vowelcount = 0;

        Console console = System.console();
        console.format("Enter a String:");

        String text = console.readLine();;

        for (int index = 0; index < text.length(); index++)
        {
            char letter = text.charAt(index);
            if (!isSpace(letter))
            {
                if (isConsonant(letter))
                {
                    consonants++;
                }
                else
                {
                    vowelcount++;
                }
            }
            else
            {
                spaces++;
            }
        }

        System.out.println("Vowels:" + vowelcount + "\nConsonants :" + consonants + "\nSpaces : " + spaces);
    }
}

回答by Actiwitty

Here is a simple way of doing this, Re-posting my answer from How to count vowels and consonants

这是一个简单的方法,重新发布我从如何计算元音和辅音中的答案

public static void checkVowels(String s){
    System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
    //Also eliminating spaces, if any for the consonant count
    System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}

回答by shashi

Using LinkedHashSetsince it preserves the order and does not allow duplicates

使用LinkedHashSet因为它保留了顺序并且不允许重复

//Check for vowel
public static boolean isVovel(char c) {

    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
        return true;
    }
    return false;
}

public static void main(String[] args) {
    String input = "shashi is a good boy";

    char inter;
    String vov = "";
    String con = "";
    String inp;
    int len = input.length();

    LinkedHashSet<String> vovels = new LinkedHashSet<String>();
    LinkedHashSet<String> consonents = new LinkedHashSet<String>();

    for (int i = 0; i < len; i++) {
        inter = input.charAt(i);
        inp = Character.toString(inter);

        if (isVovel(inter)) {
            vov = Character.toString(inter);
            vovels.add(vov);
        } 
        else {
            con = Character.toString(inter);
            consonents.add(con);
        }
    }
    Iterator<String> it = consonents.iterator();

    while (it.hasNext()) {
        String value = it.next();
        if (" ".equals(value)) {
            it.remove();
        }
    }
    System.out.println(vovels);
    System.out.println(consonents);
}

回答by shane

This example is a Class that reads text from a file as a String, stores this text as a char array, and itterates each element of the array converting the element to a String and seeing if it matches a consonant regex or a vowel regex. It increments the consonantCount or vowelCount depending on the regex match and finally prints out the counts.

这个例子是一个类,它从文件中读取文本作为字符串,将此文本存储为字符数组,并迭代数组的每个元素,将元素转换为字符串并查看它是否与辅音正则表达式或元音正则表达式匹配。它根据正则表达式匹配增加辅音计数或元音计数,并最终打印出计数。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;

public class CountVowlesAndConsonants {

public static void main (String [] args) throws IOException{
    CountVowlesAndConsonants countVowlesAndConsonants = new CountVowlesAndConsonants();
    countVowlesAndConsonants.countConsonatsAndVowles("/Users/johndoe/file.txt");

}
public void countConsonatsAndVowles(String file) throws IOException {
     String text = readFile(file);
     Pattern c = Pattern.compile("^(?![aeiouy]+)([a-z]+)$");
     Pattern v = Pattern.compile("^[aeiouy]+$");

     int vowelCount = 0;
     int consonantCount = 0;

     char [] textArray = text.toLowerCase().toCharArray();
     for( char textArraz : textArray ){
         String s = String.valueOf(textArraz);
         if(c.matcher(s).matches()) {
             consonantCount++;
         } else if (v.matcher(s).matches()) {
             vowelCount++;
         }
     }

     System.out.println("VowelCount is " + vowelCount + " Constant Count " + consonantCount);
}

public String readFile(String file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader (file));
    String         line = null;
    StringBuilder  stringBuilder = new StringBuilder();

    try {
        while((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    } finally {
        reader.close();
    }
}
}

回答by Hiago Balbino

I needed to do this function using 'loops for', follow the example in JavaScript:

我需要使用 'loops for' 来完成这个函数,按照 JavaScript 中的例子:

const defaultListVowels = ['a', 'e', 'i', 'o', 'u'];

function isVowel(value) {
    return defaultListVowels.indexOf(value) >= 0;
}

function printLetters(values) {
    console.log(values + '\r');
}

function vowelsAndConsonants(s) {
    var consonants = [];
    var vowels = [];

    for (let letter of s) {
        if (isVowel(letter)) {
            vowels.push(letter);
        } else {
            consonants.push(letter);
        }
    }

    vowels.forEach(printLetters);
    consonants.forEach(printLetters);
}