幾種統計一段字符串中所有字符出現次數的方法

1.

import java.util.ArrayList;
import java.util.HashSet;

public class NotSame {
 public static void statTimes(String param){
  if(param==null){
   return;
  }
  //hashset保存不重複的值 因此
  HashSet<Character> hSet=new HashSet<Character>();
  char[] cs=param.toCharArray();
  for(char c:cs){
   hSet.add(c);
  }
  ArrayList<Character> list=new ArrayList<Character>(hSet);
  int n=hSet.size();//有多少種字符
  int [] times=new int[n];//保存每種字符的出現次數
  
  for(char c:cs){
   times[list.indexOf(c)]++;
  }
  for(int i=0;i<n;i++){
   System.out.println("字符"+list.get(i)+"出現了:"+times[i]+"次");
   //打印結果
  }
 }
 public static void main(String[] args) {
  statTimes("asdasdasdasd!!!@@@###$$$%%^^&&**(())__++||\\");
 }
}

 

2.

import java.util.Arrays;

public class WorkDemo {
 public static void main(String[] args) {
  String str="abcdzkasdasdfka";//定義字符串
  char arr[]=str.toCharArray();//轉換成字符數組
  Arrays.sort(arr);//排序數組
  String temp=new String(arr);//重新產生字符串
  
  //便利統計
  for(int startIndex=0;startIndex<str.length();){
   char c=temp.charAt(startIndex);//獲取第一個相同字符
   String t=String.valueOf(c);//把第一個字符轉換成字符串
   //獲取字符最後出現的位置
   int lastIndex=temp.lastIndexOf(t);
   System.out.println(t+"出現的次數爲"+(lastIndex+1-startIndex));
   startIndex=lastIndex+1;//下次開始的位置
  }
 }
}

 

3.

//實現顯示字符串每個字符出現的次數
public class XXX {
 public static void main(String[] args) {
  String str="asddsaffhgwr";
  String zhongjian="";//存儲比較完之後的字符
  for(int i=0;i<str.length();i++){
   int x=0;//記每個不同字符出現的次數
   boolean flag=false;//設置布爾值,確定什麼時候自增
   char c1=str.charAt(i);
   for(int b=0;b<=zhongjian.length()-1;b++){
    if(c1==zhongjian.charAt(b)){
     flag=false;
    }
   }
   for(int m=0;m<=(str.length()-1);m++){
    if(c1==str.charAt(m)){
     x++;
    }
   }
   if(flag){
    System.out.println(c1+"出現的次數:"+x);
   }
   zhongjian+=c1;
  }
 }
}

發佈了35 篇原創文章 · 獲贊 21 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章