2014-03-06 66 views
0

我需要关于Java中的代码的帮助。Java:字符串中字符的次数

这就是问题:

示例输入:AAAAAAA

输出:A出现7.

的问题是我需要它忽略的情况。

请帮助我,我的代码工作正常,除了它不会忽略病例。

import java.io.*; 

public class letter_bmp{ 
    public static BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
    public static void main(String[] args) throws Exception 

    { 

    String string1; 
    String pick; 

    String ans; 
    do 
    { 
    int count=0; 
    System.out.print("En taro Adun, Executor! Input desired string : "); 
    string1 = input.readLine(); 
    System.out.print("Now, Executor...which character shall I choose : "); 
    pick = input.readLine(); 

    for(int counter = 0; counter < string1.length(); counter++) 
     { 
     if(pick.charAt(0) == string1.charAt(counter)) 
     count++; 
     } 
    System.out.print("Executor...you picked '" + pick + "' it is used " + count + " times in the word "+string1+"."); 

    System.out.println("\nWould you like to try again, Executor? (Yes/No): "); 
    ans = input.readLine(); 
    } 
    while(ans.equalsIgnoreCase("Yes")); 
    } 

} 
+0

哦,我没有看到我在那里放了那样的东西。 –

回答

1

使用String.toLowerCase()方法将字符串转换为小写字符。

// ... 
string1 = input.readLine().toLowerCase(); 
// ... 
pick = input.readLine().toLowerCase(); 
// ... 
+0

这是诀窍!谢谢! –

0

最简单的办法就是让2个新的字符串是这样的:

string1_lower = string1.toLowerCase(); 
pick_lower = pick.toLowerCase(); 

而且比较过程中使用这两个变量。

0

我明白这个问题已经很老了,OP可能已经得到了他的答案。但是我将这个放在这里,以防万一有人在将来需要它。

public static void main(String[] args) { 
    String s="rEmember"; 

    for(int i = 0; i <= s.length() - 1; i++){ 
     int count = 0; 
     for(int j = 0; j <= s.length() - 1; j++){ 
      if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))){ 
       count++; 
      } 
     } 
     System.out.println(s.charAt(i) + " = " + count + " times"); 
    } 

}