Ignoring uppercase and lowercase on char when comp

2020-03-29 06:36发布

The goal of this is to get a sentence from the user and determine how many of each vowel shows up.The majority of this is done except I am not sure how to ignore uppercase and lowercase letters but I am guessing equalsIgnoreCase or toUpperCase().

I'd like to also know if there is another way to do this using some other classes of String, StringBuilder, or Character. I'm still new to programming and this chapter is killing me.

    int counterA=0,counterE=0,counterI=0,counterO=0,counterU=0;
    String sentence=JOptionPane.showInputDialog("Enter a sentence for vowel count");        

    for(int i=0;i<sentence.length();i++){
        if(sentence.charAt(i)=='a'){
            counterA++;}
        else if(sentence.charAt(i)=='e'){
            counterE++;}
        else if(sentence.charAt(i)=='i'){
            counterI++;}
        else if(sentence.charAt(i)=='o'){
            counterO++;}
        else if(sentence.charAt(i)=='u'){
            counterU++;}
        }   
    String message= String.format("The count for each vowel is \nA:%d\nE:%d\nI:%d\nO:%d\nU:%d",
            counterA,counterE,counterI,counterO,counterU);  
    JOptionPane.showMessageDialog(null, message);
}

}

code here

标签: java string char
3条回答
beautiful°
2楼-- · 2020-03-29 06:46

equalsIgnoreCase or toUpperCase() method is the best (and the easiest) option.

查看更多
我只想做你的唯一
3楼-- · 2020-03-29 06:52

Since you are comparing on primitive char,

Character.toLowerCase(sentence.charAt(i))=='a'      
Character.toUpperCase(sentence.charAt(i))=='A' 

should already be the best way for your case in Java.

But if you are comparing on Stirng

 sentence.substring(i,i+1).equalsIgnoreCase("a")

will be more direct , but a little bit harder to read.

If you have a String type inside an array or list, calling

s.equalsIgnoreCase("a") 

will be much better. Please note that you are now comparing with "a" not 'a'.

If you are using StringBuilder/StringBuffer, you can call toString(), and then use the same method.

sb.toString().substring(i,i+1).equalsIgnoreCase("a");
查看更多
男人必须洒脱
4楼-- · 2020-03-29 07:04

Use equalsIgnoreCase looks like it is more readable than converting both Strings to uppercase before a comparison. Readability trumps micro-optimization.

below looks more readable

if (myString.toUpperCase().equals(myAnotherString.toUpperCase())) {

or

if (myString.equalsIgnoreCase(myAnotherString))
查看更多
登录 后发表回答