统计每一次个字符串中每个字符出现的次数
做法一:面向对象的做法
package string;
import java.util.Arrays;
public class Demo1 {
public static void main(String[] args) {
String s = "..adsa5640!!6DS65d01.!!...sd6DVWUQY!d6!540..";//8个.
MyChar[] mcs = {};
for (int i = 0; i < s.length(); i++) {
MyChar mc = isExists(mcs , s.charAt(i));
if (mc == null){
mcs = Arrays.copyOf(mcs, mcs.length + 1);
mcs[mcs.length - 1] = new MyChar( 1 , s.charAt(i));
}else{
mc.setCount(mc.getCount()+1);
}
}
Arrays.sort(mcs);
show(mcs);
}
//数组遍历
private static void show(MyChar[] mcs) {
for(MyChar mc : mcs){
System.out.println(mc);
}
}
//判断是否存在
private static MyChar isExists(MyChar[] mcs, char charAt) {
for(MyChar mc : mcs){
if (mc.getC() == charAt)
return mc;
}
return null;
}
}
//定义一个类记录字符和出现的次数
class MyChar implements Comparable<MyChar> {
int count;
char c;
@Override
public String toString() {
return c + ":\t" + count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
public MyChar() {
}
public MyChar(int count, char c) {
this.count = count;
this.c = c;
}
//正向排序
@Override
public int compareTo(MyChar mc) {
return this.c - mc.c;
}
}
做法二
package string;
public class Demo2 {
public static void main(String[] args) {
String s = "..adsa5640!!6DS65d01.!!...sd6DVWUQY!d6!540..";//8个.
function(s);
}
private static void function(String s) {
String ss = s;//备份s的值
String str = "";//记录s中出现的字符
int count = 0;
while(s.length() != 0){
str += s.charAt(0);
s = s.replace(s.charAt(0) + "" , "");
}
//用备份的值进行遍历查找并计数
for (int i = 0; i < str.length(); i++) {
count = 0;
for (int j = 0; j < ss.length(); j++) {
if (str.charAt(i) == ss.charAt(j)){
count++;
}
}
System.out.println(str.charAt(i) + ": " + count);
}
}
}