2014-03-06 69 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"); 
    } 

}