Java程序来计算每个字符的出现次数

编写一个Java程序,打印每个字符的出现次数,并且不应重复打印重复字符的出现次数,如示例所示: 例如:

null
Input : geeksforgeeksOutput :Number of Occurrence of g is:2Number of Occurrence of e is:4Number of Occurrence of k is:2Number of Occurrence of s is:2Number of Occurrence of f is:1Number of Occurrence of o is:1Number of Occurrence of r is:1

方法:

其想法是创建一个大小为256的计数数组。遍历输入字符串,并为每个字符增加其计数。

JAVA

// Java program for the above approach
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)]);
}
}
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
getOccuringChar(str);
}
}


输出:

Number of Occurrence of g is:2Number of Occurrence of e is:4Number of Occurrence of k is:2Number of Occurrence of s is:2Number of Occurrence of f is:1Number of Occurrence of o is:1Number of Occurrence of r is:1
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享