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上的大写和小写
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
