字符串中的LowerCase和upperCase

时间:2013-11-25 16:40:47

标签: java

这是我的课程,用于查找句子中的空格量,元音量和辅音数量。它工作正常,但我需要它忽略案件。我该怎么做呢?我熟悉“忽略大小写”代码,但我不确定将它放在这个特定程序中的哪个位置。

            public class Counting{
            private String sentence;
            private int spaces;
            private int vowels;
            private int consonants;


            public Counting(){
                sentence = new String();
                spaces = 0;
                vowels = 0;
                consonants = 0;

            }

            public void setSentence(String sentence){
                this.sentence = sentence;
            }

            public void compute(){
                for(int i =0; i < sentence.length();i++){
                    char letter = sentence.charAt(i);
                        if(sentence.charAt(i)==' ' ){
                            spaces++;

                            }
                        else if((letter=='a')||(letter=='e')
                                 ||(letter=='i')||(letter=='o')||(letter=='u'))
                                    vowels++;

                        else{
        consonants++;
        }
        }
                            }

            public int getSpaces(){
                 return spaces;
            }

            public int getVowels(){
    return vowels;
        }
public int getConsonants(){
    return consonants;
            }

}

7 个答案:

答案 0 :(得分:3)

执行此操作的常用方法是将原始字符串简单地转换为全部小写。

答案 1 :(得分:2)

将传递给您的类的字符串转换为小写:

        public Counting(){  
            setSentence("");
            spaces = 0;
            vowels = 0;
            consonants = 0;

        }

        public void setSentence(String sentence){
            this.sentence = sentence.toLowerCase();
        }

答案 2 :(得分:2)

使用

letter.equalsIgnoreCase("a")

检查letterA还是a

答案 3 :(得分:2)

维护一组所有元音和辅音可能会更容易,包括大写和小写 - 你的代码将包含数字和标点符号作为辅音

if (consonents.contains(c)) consonents++;
else if (vowels.contains(c)) vowels++;
else if (spaces.contains(c)) spaces++

或者你可以保留一个char和property的地图(一个从0开始并增加1并包含misc作为catch all的枚举)然后只保留一个属性计数数组:

counts[property.get(c)]++;

答案 4 :(得分:1)

将其放入compute()方法中。这不是很有效,但这是最简单的事情。

public void compute() {
    String lowerCaseSentence = sentence.toLowerCase();
    //...
}

sentence

的其余代码中将lowerCaseSentence替换为compute()

答案 5 :(得分:1)

是的,最好的方法是将整个输入句子转换成大写或小写,并对其执行所需的操作

答案 6 :(得分:1)

试一试:

sentence.toLowerCase();
相关问题