`
SurpriseLee
  • 浏览: 7269 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

统计字符串中每个字符出现的次数

    博客分类:
  • Java
阅读更多
这篇博客是主要关于统计每个字符在字符串中出现次数的程序算法,以下
是我的代码示例:Java代码
public class Count {   
    public static void main(String[] args) {   
        String str = "abcdefgabcdabcdeabcdabcaba";   
        Count count = new Count();   
        for (int i = 0; i < str.length(); i++) {   
            int n = 0;   
            for (int j = 0; j < i; j++) {   
                // 判断要统计的字符是否被统计过(n!=0:被统计过;n=0:未被统计)   
                if (String.valueOf(str.charAt(j)).equals(   
                        String.valueOf(str.charAt(i)))) {   
                    ++n;   
                }   
            }   
            if (n == 0) {   
                count.cout(str.charAt(i), str);   
            }   
        }   
    }   
  
    /**  
     * 统计字符a在字符串str中出现次数的函数  
     *   
     * @param a  
     * @param str  
     */  
    public void cout(char a, String str) {   
        int j = 0;   
        for (int i = 0; i < str.length(); i++) {   
            if (String.valueOf(a).equals(String.valueOf(str.charAt(i)))) {   
                j++;   
            }   
        }   
        System.out.println(a + "出现" + j + "次");   
    }   
}  

public class Count { 
public static void main(String[] args) { 
String str = "euriyui3743289^%^&*&DJHK2312"; 
Count count = new Count(); 
for (int i = 0; i < str.length(); i++) { 
int n = 0; 
for (int j = 0; j < i; j++) { 
// 判断要统计的字符是否被统计过(n!=0:被统计过;n=0:未被统计) 
if (String.valueOf(str.charAt(j)).equals( 
String.valueOf(str.charAt(i)))) { 
++n; 
} 
} 
if (n == 0) { 
count.cout(str.charAt(i), str); 
} 
} 
} 

/** 
* 统计字符a在字符串str中出现次数的函数 
* 
* @param a 
* @param str 
*/ 
public void cout(char a, String str) { 
int j = 0; 
for (int i = 0; i < str.length(); i++) { 
if (String.valueOf(a).equals(String.valueOf(str.charAt(i)))) { 
j++; 
} 
} 
System.out.println(a + "出现" + j + "次"); 
} 
} 


运行结果:
a出现7次
b出现6次
c出现5次
d出现4次
e出现3次
f出现2次
g出现1次

主要思路:
1.定义一个方法cout,两个参数char a,String str
作用:统计字符a在字符串str中出现的次数
2.在主函数中用一个循环for (int i = 0; i < str.length(); i++) ,轮流调用cout函数就可以统计出想要的结果
3.但是为了避免被重复统计,需要在上述循环内嵌入一个循环
for (int j = 0; j < i; j++)
目的:判断是否已经被统计过,如果n不等于0,说明已经被统计过,就不需要调用cout方法

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics