package qin.com;
import java.util.Arrays;
//去除一个字符串中字母出现的次数,如字符串“fdsafadsfdfew124”,
//输出格式为:a(2)b(3)c(1)……
public class Demo {
public static void main(String[] args)
{
String q = "fdsafadsfdfew124";
System.out.println(getNum(q));
}
public static StringBuffer getNum(String x){
StringBuffer sb = new StringBuffer();
char[] w = x.toCharArray();//将字符串转换成字符数组
Arrays.sort(w);//对字符数组的排序
int counter=1;
for(int i=0;i<w.length-1;i++){
q:for(int j = i+1;j<w.length;j++){
if(w[i]==w[j]){
counter++;
}
else{ break q;}
}//依次对比,直到不相同,用counter记录出现的次数
sb.append(w[i]+"("+counter+")");
i = counter-1;//字母出现的次数-1,做为下一个开始对比的数的角标
counter = 1;//重置计数器
}
return sb;
}
}
编译器提示的错误是Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
|