Ignoring uppercase and lowercase on char when comparing(比较时忽略char上的大写和小写)
问题描述
这样做的目的是从用户那里得到一个句子并确定每个元音出现了多少.除了我不确定如何忽略大写和小写字母但我猜是 equalsIgnoreCase 或 toUpperCase().
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().
我还想知道是否有其他方法可以使用其他一些 String、StringBuilder 或 Character 类.我对编程还是很陌生,这一章让我很生气.
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
A:%d
E:%d
I:%d
O:%d
U:%d",
counterA,counterE,counterI,counterO,counterU);
JOptionPane.showMessageDialog(null, message);
}
}
代码在这里
推荐答案
由于你是在原始字符上进行比较,
Since you are comparing on primitive char,
Character.toLowerCase(sentence.charAt(i))=='a'
Character.toUpperCase(sentence.charAt(i))=='A'
应该已经是您在 Java 中的最佳方式了.
should already be the best way for your case in Java.
但是如果你在 Stirng 上进行比较
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.
如果数组或列表中有 String 类型,则调用
If you have a String type inside an array or list, calling
s.equalsIgnoreCase("a")
会好很多.请注意,您现在是在与a"而不是a"进行比较.
will be much better. Please note that you are now comparing with "a" not 'a'.
如果你使用StringBuilder/StringBuffer,你可以调用toString(),然后使用同样的方法.
If you are using StringBuilder/StringBuffer, you can call toString(), and then use the same method.
sb.toString().substring(i,i+1).equalsIgnoreCase("a");
这篇关于比较时忽略char上的大写和小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较时忽略char上的大写和小写
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
