2012-06-03 66 views
8

我有一个家庭作业分配来计算字符串中的特定字符。计算字符串中的特定字符(Java)

例如:string = "America"

输出应该=以上a appear 2 times, m appear 1 time, e appear 1 time, r appear 1 time, i appear 1 time and c appear 1 time

public class switchbobo { 

/** 
* @param args 
*/  // TODO Auto-generated method stub 
    public static void main(String[] args){ 
    String s = "BUNANA"; 
    String lower = s.toLowerCase(); 
    char[] c = lower.toCharArray(); // converting to a char array 
    int freq =0, freq2 = 0,freq3 = 0,freq4=0,freq5 = 0; 

    for(int i = 0; i< c.length;i++) { 
     if(c[i]=='a') // looking for 'a' only 
      freq++; 
     if(c[i]=='b') 
      freq2++; 
     if (c[i]=='c') { 
      freq3++; 
     } 

     if (c[i]=='d') { 
      freq4++; 
     }  
    } 
    System.out.println("Total chars "+c.length); 
    if (freq > 0) { 
     System.out.println("Number of 'a' are "+freq); 
    } 
    } 
} 

代码为我做了什么,但我认为这是没有意义的有26个变量(一个用于每个字母)。你们有替代结果吗?

+1

使用一个阵列,26个索引。 (''a' - 'a'== 0,'b' - 'a'== 1',等等)。 – Jeffrey

回答

7

显然你对每个字母有一个变量的直觉是正确的。

问题是,您没有任何自动化的方式来对不同的变量进行相同的工作,您没有任何简单的语法可以帮助您为26种不同的工作进行相同的工作(计算单个字符频率)变量。

那么你能做什么?我会提示你向两个解决方案:

  • 你可以使用数组(但你必须找到一种方法来映射字符a-z到指数0-25,这是有点琐碎的是你对ASCII编码的原因)
  • 你可以使用一个HashMap<Character, Integer>这是一个关联容器,在这种情况下,可以让你有映射到特定的字符,数字,因此完全符合您的需求
+0

番石榴也可以使用['Multiset '](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multiset.html),但这可能是矫枉过正作业:) –

4

您可以使用字符键和Integer值的HashMap

HashMap<Character,Integer> 

迭代通过串

-if the character exists in the map get the Integer value and increment it. 
-if not then insert it to map and set the integer value for 0 

这是一个伪代码,你必须尝试编码它

+0

这将解决任何角色。我喜欢。 –

0

在延续杰克的答案下面的代码可能是您的解决方案。它使用一个数组来存储字符的频率。

public class SwitchBobo 
{ 
    public static void main(String[] args) 
    { 
     String s = "BUNANA"; 
     String lower = s.toLowerCase(); 
     char[] c = lower.toCharArray(); 
     int[] freq = new int[26]; 
     for(int i = 0; i< c.length;i++) 
     { 
     if(c[i] <= 122) 
     { 
      if(c[i] >= 97) 
      { 
       freq[(c[i]-97)]++; 
      } 
     }   
     } 
     System.out.println("Total chars " + c.length); 
     for(int i = 0; i < 26; i++) 
     { 
     if(freq[i] != 0) 
      System.out.println(((char)(i+97)) + "\t" + freq[i]); 
     }  
    } 
} 

它会给下面的输出:

Total chars 6 
a  2 
b  1 
n  2 
u  1 
+0

关于代码c [i] -97,会按预期工作吗?这是我的一个嫌疑犯,因为变量c是char类型,并且它减去了一个整数。在C语言中,你可以使它工作,但Java是一种更严格的打字语言。因此我不鼓励它。使用ASCII编码更安全,更传统。例如,字母'a'的ASCII值是什么? –

+0

@TheOriginalAndroid:是的。如果没有,我不会发布它。 '在字符和整数之间执行算术运算时,它实际上是在字符的ascii值和整数之间执行的。这种操作的结果也是一个整数。''a'的ascii值是97! – WickeD

2

我使用的解决方案是一个HashMap。

import java.util.*; 

public class Sample2 { 

/** 
* @param args 
*/ 
public static void main(String[] args) 
{ 
    HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 
    String test = "BUNANA"; 
    char[] chars = test.toCharArray(); 

    for(int i=0; i<chars.length;i++) 
    { 
     if(!map.containsKey(chars[i])) 
     { 
      map.put(chars[i], 1); 
     } 
     map.put(chars[i], map.get(chars[i])+1); 
    } 

    System.out.println(map.toString()); 
} 

} 

产生的输出 - {U = 2,A = 3,B = 2,N = 3}

+0

你试过了吗?因为它给每个字母 – David

+0

+1,你已经忘记了其他的,它很好地工作,谢谢! – David

0
int a[]=new int[26];//default with count as 0 
for each chars at string 
if (String having uppercase) 
    a[chars-'A' ]++ 
if lowercase 
then a[chars-'a']++ 
0
public class TestCharCount { 
    public static void main(String args[]) { 
     String s = "america"; 
     int len = s.length(); 
     char[] c = s.toCharArray(); 
     int ct = 0; 
     for (int i = 0; i < len; i++) { 
      ct = 1; 
      for (int j = i + 1; j < len; j++) { 
       if (c[i] == ' ') 
        break; 
       if (c[i] == c[j]) { 
        ct++; 
        c[j] = ' '; 
       } 

      } 
      if (c[i] != ' ') 
       System.out.println("number of occurance(s) of " + c[i] + ":" 
         + ct); 

     } 
    } 
} 
+1

欢迎使用stackoverflow,如果你提供一些解释来跟随你的代码,它会有所帮助。这种方式,而不是复制/粘贴,并希望它的作品,问问题的人将能够看到为什么有效的,为什么没有 – smerny

0

也许可以使用此

public static int CountInstanceOfChar(String text, char character ) { 
    char[] listOfChars = text.toCharArray(); 
    int total = 0 ; 
    for(int charIndex = 0 ; charIndex < listOfChars.length ; charIndex++) 
     if(listOfChars[charIndex] == character) 
      total++; 
    return total; 
} 

例如:

String text = "america"; 
char charToFind = 'a'; 
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times"); 
0

在字符串中计数char'l'。

String test = "Hello"; 
    int count=0; 
    for(int i=0;i<test.length();i++){ 
    if(test.charAt(i)== 'l'){ 
     count++; 
     } 
    } 

int count= StringUtils.countMatches("Hello", "l");