编写一个Java程序, 该程序打印每个字符出现的次数, 并且也不应重复打印重复字符的出现, 如示例中所示:
例子:
Input : lsbin
Output :
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1
这个想法是创建一个大小为256的计数数组。遍历输入字符串, 并为每个字符增加其计数。
class NoOfOccurenceOfCharacters {
static final int MAX_CHAR = 256 ;
static void getOccuringChar(String str)
{
//Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int [MAX_CHAR];
int len = str.length();
//Initialize count array index
for ( int i = 0 ;
i <
len;
i++)
count[str.charAt(i)]++;
//Create an array of given String size
char ch[] = new char [str.length()];
for ( int i = 0 ;
i <
len;
i++) {
ch[i] = str.charAt(i);
int find = 0 ;
for ( int j = 0 ;
j <
= i;
j++) {//If any matches found
if (str.charAt(i) == ch[j])
find++;
}if (find == 1 )
System.out.println( "Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = "lsbin" ;
getOccuringChar(str);
}
}
【Java程序统计每个字符的出现次数】输出如下:
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1
推荐阅读
- 签证面试经验|实习(校园内)
- win7系统游戏手柄怎样用?
- win7系统剪切板怎样打开?
- win7 运行在啥地方里?win7 运行位置介绍
- Win7系统旗舰版Winmgmt.exe文件出错的处理办法
- Win7已激活,微软正版验证显示:不是正版的处理办法
- 怎样处理Win7网上看视频绿屏的问题?
- win7系统为啥一开页面就卡?
- win7 旗舰版 专业版的区别