字符串去重,并打印出现次数

//方法一,字符串直接去截取

//*******************************

int times = 1;//出现次数
int printTimes = 1;//初始化打印次数
String ss = "nabcnnnm1112你好";
String printString = "";
for (int i = 0; i < ss.length(); i++) {
String s = ss.charAt(i) + "";
if(!printString.contains(s)){
printString+=s;
printTimes=1;
//System.out.println(printString);
}else{
printTimes++;
}
String parentString = ss;
String subString = parentString.substring(ss.indexOf(s) + 1);
times = 1;
// 开始查找的位置
int indexStart = 0;
boolean sFlag = true;
// 索引字符串判断(多次)
if (subString.indexOf(s) != -1) {
while (sFlag) {
times++;
parentString = subString;
subString = parentString.substring(subString.indexOf(s) + 1);
if (subString.indexOf(s) == -1) {
sFlag = false;
}
}
}
//控制打印次数
if(printTimes == 1){
System.out.println(s + "=" + times);
}

}



方法二,利用Java集合(较简单)

//*******************************

String ss = "nabcnnnm1112你好";
Map map =  new HashMap();
for (int i = 0; i < ss.length(); i++) {
String c = ss.charAt(i)+"";
if(map.containsKey(c)){
int value = map.get(c);
value+=1;
map.put(c, value);

}else{
map.put(c, 1);
}
}
for (Iterator it = map.keySet().iterator();it.hasNext();) {
String key = it.next();//特别注意
System.out.println(":"+key+"="+map.get((key)));
}

}



你可能感兴趣的:(java)