java 在java中检查字符串中是否有辅音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17440444/
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-11-01 01:59:00  来源:igfitidea点击:

Check if there is a consonant in a string in java

java

提问by DLJ

So I am writing a program that is the game called pig latin (You can check Wikipedia for the rules, but it consits of taking the first consonants and moving them to the back of the word and adding -ay). I need to check the word has any consonants in the beginning of the word . If it has a or more consants the it needs to get the substring starting at the first consonant and ending at the last consonant before a vowel.

所以我正在编写一个程序,它是一个叫做猪拉丁语的游戏(你可以查看维基百科的规则,但它包括取第一个辅音并将它们移到单词的后面并添加 -ay)。我需要检查单词的开头是否有辅音。如果它有一个或多个辅音,它需要获取从第一个辅音开始到元音前最后一个辅音结束的子串。

public void isConsonant(String word){
    char[] consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm'
            , 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z' };
    char[] StringArray = word.toCharArray();
    for(int dex = 0; dex < StringArray.length; dex++ ){
        char current = StringArray[dex];
    }
}

Here is an example:

下面是一个例子:

The word 'glove' should become oveglay . My program outputs 'lovegay'.

“手套”这个词应该变成 oveglay 。我的程序输出'lovegay'。

Here is my program (minus importsand GUIstuff):

这是我的程序(减号importsGUI东西):

public class PigLatin extends JFrame implements ActionListener {
    JTextField word = new JTextField(25);
    JButton GO = new JButton("Go");
    JLabel output = new JLabel();
    String CharNum1;
    String CharNum2;

    //The frame setup should be here

    public void isConsonant(String verify) {
        char[] consonants = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
                'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z' };
        char[] StringArray = verify.toCharArray();
        for (int dex = 0; dex < StringArray.length; dex++) {
            char current = StringArray[dex];
        }
    }

    public void game() {
        // The actual word
        String word2 = word.getText();

        // The first character
        CharNum1 = word2.substring(0, 2);
        CharNum2 = word2.substring(1, word2.length());

        // Remove the first char
        // String RevampedWord = word2.replace(CharNum1, "");
        String finalWord = CharNum2 + "-" + CharNum1 + "ay";
        output.setText(finalWord);
    }

    public void actionPerformed(ActionEvent event) {
        game();
    }

    public static void main(String[] arguments) {
        PigLatin pig = new PigLatin();
    }
}

So my question is weather it is possible to see if a String contains consonats and make a substring of the first consonant to the first consonant before a vowel.

所以我的问题是天气是否有可能看到一个字符串是否包含辅音并将第一个辅音的子串变成元音之前的第一个辅音。

Thanks in advance.

提前致谢。

回答by Bohemian

You're barking up the wrong tree... use regex:

你吠错了树......使用正则表达式:

To extract all consonants up to the first vowel:

提取直到第一个元音的所有辅音:

String initialConsonants = str.replaceAll("([^aeiouAEIOU]*).*", "");

To extract just the consonants:

只提取辅音:

String onlyConsonants = str.replaceAll("[aeiouAEIOU]", "");

or if you really need to know if the text is all consonants:

或者如果您真的需要知道文本是否都是辅音:

boolean isAllConsonants = str.matches("[^aeiouAEIOU]+");

回答by Dennis Meng

One way of possibly doing what you want that is a little intriguing:

一种可能做你想做的事情的方法有点有趣:

Supposing that you are turning wordinto pig latin, what about using word.split("[aeiouAEIOU]", 2)? Looking at the docs for split, it'll match the regex exactly once, so the array of strings returned will be split around the first vowel in the word. You can then put those pieces back into the right order based on whether the first vowel was the first char, last char, somewhere in between, or even nowhere to be found (remember, not all words contain one of those five vowels).

假设你正在word变成猪拉丁语,那么使用word.split("[aeiouAEIOU]", 2)? 查看 的文档split,它将与正则表达式完全匹配一次,因此返回的字符串数组将围绕单词中的第一个元音进行拆分。然后,您可以根据第一个元音是第一个字符、最后一个字符、介于两者之间或什至无处可找到(请记住,并非所有单词都包含这五个元音之一),将这些片段重新按正确顺序排列。

(Note that splitwill remove the first vowel if it finds it, so you'll have to use wordto get that vowel back, but the size of the first piece will also be that vowel's index into word.)

(请注意,split如果找到第一个元音,它将删除它,因此您必须使用它word来恢复该元音,但第一部分的大小也将是该元音的索引word。)

回答by John

Instead of writing big , have a boolean function that would check in that char is vowel

不是写 big ,而是有一个布尔函数来检查那个字符是元音

eg

例如

public static boolean isVowel(final char ch) {
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';

}

Check for each and every character and then you can easily code it out.

检查每个字符,然后您可以轻松地将其编码。

回答by maqjav

Here you have it, I erased your isConsonantfunction and made a new one to get the first portion of the String that only contains constants.

在这里,我删除了您的isConsonant函数并创建了一个新函数以获取仅包含常量的 String 的第一部分。

The game function is modified with this change:

游戏功能修改如下:

public String getFirstConsonants(String verify) {
    List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u'); // better finding vowels (faster)

    String firstString = "";
    for (int i = 0; i < verify.length(); i++) {
        if (!vowels.contains(verify.charAt(i)))
            firstString += verify.charAt(i); // we found a constant
        else
            break; // we found a vowel, we have already our string
        }

    return firstString;
}

public void game() {
    // The actual word
    String word2 = word.getText();

    // Lets find the first consonants
    String firstString = getFirstConsonants(word2);

    String finalWord = word2.substring(firstString.length()) + "-" + firstString + "ay";
    output.setText(finalWord);
}

回答by Max Kryvych

Here are some 1-line routines to detect if a certain character is a consonant or vowel:

以下是一些用于检测某个字符是辅音还是元音的 1 行例程:

private static boolean isVowel(char c) {
    return "aeiouAEIOU".contains(String.valueOf(c));
}

private static boolean isConsonant(char c) {
    return "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ".contains(String.valueOf(c));
}