Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java đếm ký tự trong mỗi từ của câu cho trước


Để đếm ký tự trong mỗi từ của câu cho trước, mã Java như sau:

Ví dụ

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);    } }

Kết quả

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

Lớp Demo chứa hàm char_occurence lặp qua chuỗi đếm mỗi ký tự gán đếm cho ký tự tương ứng trong mảng count. Trong main, đối tượng Scanner tạo đọc input từ console. Hàm gọi trên chuỗi và đếm mỗi ký tự hiển thị.