ในการนับอักขระในแต่ละคำในประโยคที่กำหนด รหัส Java เป็นดังนี้ −
ตัวอย่าง
import java.util.*;
public class Demo{
static final int max_chars = 256;
static void char_occurence(String my_str){
int count[] = new int[max_chars];
int str_len = my_str.length();
for (int i = 0; i < str_len; i++)
count[my_str.charAt(i)]++;
char ch[] = new char[my_str.length()];
for (int i = 0; i < str_len; i++){
ch[i] = my_str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++){
if (my_str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("The number of occurrence of " + my_str.charAt(i) + " is :" +
count[my_str.charAt(i)]);
}
}
public static void main(String[] args){
Scanner my_scan = new Scanner(System.in);
String my_str = "This is a sample";
char_occurence(my_str);
}
} ผลลัพธ์
The number of occurrence of T is :1 The number of occurrence of h is :1 The number of occurrence of i is :2 The number of occurrence of s is :3 The number of occurrence of is :3 The number of occurrence of a is :2 The number of occurrence of m is :1 The number of occurrence of p is :1 The number of occurrence of l is :1 The number of occurrence of e is :1
คลาสชื่อ Demo มีฟังก์ชัน 'char_occurence' ที่วนซ้ำผ่านสตริงและนับทุกอักขระ และกำหนดจำนวนให้กับอักขระที่เกี่ยวข้องในอาร์เรย์การนับ ในฟังก์ชันหลัก อ็อบเจ็กต์คลาส Scanner จะถูกสร้างขึ้นเพื่ออ่านอินพุตจากคอนโซล ฟังก์ชันนี้เรียกใช้บนสตริงและจำนวนอักขระทุกตัวจะแสดงบนคอนโซล