java中輸出一個字串中出現次數最多的字元以及次數
阿新 • • 發佈:2018-12-18
- 1 先把字串轉化為陣列 .toCharArray
- 2 定義一個數組count[i] 存取每個字元 以及數量 count[i]++
- 3 計算每個字元 以及值
- 4 取count的最大值
public class MaxString {
public static void main(String[] args) {
String s="aaahssjshsssssshwws123222";
// 轉化為字元陣列。
char[] c=s.toCharArray();
// 定義一個數組存次數
int [] count=new int[c.length];
//把每個對應的值以及次數存下來
for(int i=0;i<=c.length-1;i++)
{
char mid=c[i];
for(int j=0;j<=c.length-1;j++)
{
if(mid==c[j])
count[i]++;
}
}
// 取出count陣列的最大值,並且得到下標
int index=0;
int max=0;
for(int i=0;i<=c.length-1;i++)
{
if(max<=count[i])
{
max=count[i];
index= i;
}
}
System.out.println("出現最多的字元是:"+c[index]+"出現最多的次數是:"+count[index]);
}
}