面向对象思想实现对一个字符串每一个字符出现次数的计数(新手,看看就行,勿喷)
首先创建一个类,用来存储遍历到的字符(不重复的)
class Char{
private char ch;
private int count;
@Override
public String toString() {
return "Char{" +
"ch=" + ch +
", count=" + count +
'}';
}
public char getCh() {
return ch;
}
public void setCh(char ch) {
this.ch = ch;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Char(char ch, int count) {
this.ch = ch;
this.count = count;
}
public Char() {
}
}
主函数
public static void main(String[] args) {
String s = "fdsfhasdshdsgdg";
//设定一个char数组,将遍历到的放进去的同时,一边做判断,一边放进去
Char[] chars = {};
//遍历字符串
for(int i = 0;i < s.length();i++){
char c = s.charAt(i);
//在此处应该做一个判断,判断是添加过的还是第一次遍历到的
//存在过的:count++,如果是第一次遍历到,则放进字符数组,然后默认为1
Char find = getFind(c, chars);
if(find != null){
int count = find.getCount();
count++;
}else{
Char[] chars1 = Arrays.copyOf(chars, chars.length + 1);
Char c1 = new Char();
c1.setCh(c);
c1.setCount(1);
chars1[chars1.length - 1] = c1;
chars = chars1;
}
}
//遍历
System.out.println("字符\t个数");
for(Char e : chars){
System.out.println(e.getCh()+"\t"+e.getCount());
}
}
public static Char getFind(char c,Char[] chars){
//遍历字符数组,判断
for(Char e : chars){
if(e.getCh() == c){
return e;
}
}
return null;
}