주어진 문장에서 각 단어의 문자 수를 세는 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라는 클래스에는 문자열을 반복하고 모든 문자를 계산하고 count 배열의 각 문자에 해당 카운트를 할당하는 'char_occurence' 함수가 포함되어 있습니다. 기본 기능에서 Scanner 클래스 개체가 생성되어 콘솔에서 입력을 읽습니다. 함수는 문자열에 대해 호출되고 모든 문자의 수가 콘솔에 표시됩니다.