TextAnalyser ,分析文本中的字母出现次数、百分比等

碰巧要做这个作业的同学低调地参考一下



public class TextAnalyser {

private int total=0;
private int[] charCount = new int[26]; //this array stores number of chars



public TextAnalyser()
{

}

public TextAnalyser(String initial)
{

this.analyse(initial);
}

public void analyse(String str)
{
//restore all chars to lower case
str = str.toLowerCase();

//index of current letter
int index = 0;

//letters number
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(Character.isLetter(ch))
{
total++;
}
}

//count the char number
for(char charInitial = 'a';charInitial<=(char)('a'+25);charInitial++)
{
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(charInitial==ch)
{
charCount[index]++;
}

}
index++;
}

}

public int charsAnalysed()
{
return total;
}

public int frequency(char c)
{
c = Character.toLowerCase(c);
return charCount[getCharIndex(c)];
}


public double percentage(char c)
{
c = Character.toLowerCase(c);

double percentage = 0.0;

if(total==0||frequency(c)==0)
return 0.0;

percentage = (double)frequency(c)/total*100;

return percentage;

}

public char mostFrequent()
{
if(total==0)
return '?';

int maxCount=0;
int index = 0;
char mostFrequentChar = '?';
for(char charInitial = 'a';charInitial<=(char)('a'+25);charInitial++)
{
if(charCount[index]>=maxCount)
{
maxCount=charCount[index];
mostFrequentChar=charInitial;
}
index++;
}

return mostFrequentChar;
}

public void clear()
{
total = 0;
charCount = new int[26];
}





//private helper methods

//return the index of given char of charCount array
private int getCharIndex(char ch)
{
return ch-'a';
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值