【问题标题】:How to Ignore Case如何忽略大小写
【发布时间】:2018-01-09 21:09:37
【问题描述】:

我这里有这段代码,它读取一个字符串和一个字符,然后在该字符串中找到该字符的所有出现。但是,它只找到特定的大小写,我如何让它检测大小写?

String str = oIn.nextLine();
char ch = oIn.nextLine().charAt(0); 
int count = 0;
int index = str.indexOf(ch);

while (index >= 0){
    index = str.indexOf(ch, index+1);
    count++;          
    System.out.println ("The amount of the character " + ch + " in " + str +" are " +count);
}

【问题讨论】:

  • String str = oIn.nextLine().toUpperCase();String str = oIn.nextLine().toLowerCase();
  • Character.toLowerCase将字符转为小写并比较或使用String::toLowerCase比较字符串。

标签: java string while-loop char indexof


【解决方案1】:
String str = oIn.nextLine().toLowerCase();
char ch = Character.toLowerCase(oIn.nextLine().charAt(0));
int count = 0;        
for(int i = 0; i < str.length(); i++){
   if(str.charAt(i) == ch ){
      count++;
   }
}
System.out.println ("The frequency of the character " + ch + " in " + str +" is " +count);

【讨论】:

    【解决方案2】:

    您可以在比较之前使用Character.toLowerCase 将被比较的字符转换为小写。

    即改变这个:

    char ch = oIn.nextLine().charAt(0); 
    

    到这里:

    char ch = Character.toLowerCase(oIn.nextLine().charAt(0));
    

    然后在这个字符串上调用小写:

    String str = oIn.nextLine().toLowerCase();
    

    现在您可以使用String#indexOf 来查找忽略大小写的字符的索引了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多