다음이 우리의 문자열이라고 가정해 봅시다 -
String myStr = "thisisit";
발생 횟수를 계산하기 위해 HashMap을 사용하고 있습니다. 루프를 통해 containsKey(0 및 charAt() 메서드를 사용하여 위의 문자열에서 각 문자의 발생 횟수를 계산합니다. -
HashMap <Character, Integer> hashMap = new HashMap<>();
for (int i = myStr.length() - 1; i >= 0; i--) {
if (hashMap.containsKey(myStr.charAt(i))) {
int count = hashMap.get(myStr.charAt(i));
hashMap.put(myStr.charAt(i), ++count);
} else {
hashMap.put(myStr.charAt(i),1);
}
} 예시
다음은 각 문자의 발생 횟수를 계산하는 프로그램입니다. -
import java.util.HashMap;
public class Demo {
public static void main(String[] args) {
String myStr = "thisisit";
System.out.println("String ="+myStr);
HashMap <Character, Integer> hashMap = new HashMap<>();
for (int i = myStr.length() - 1; i >= 0; i--) {
if (hashMap.containsKey(myStr.charAt(i))) {
int count = hashMap.get(myStr.charAt(i));
hashMap.put(myStr.charAt(i), ++count);
} else {
hashMap.put(myStr.charAt(i),1);
}
}
System.out.println("Counting occurrences of each character = "+hashMap);
}
} 출력
String =thisisit
Counting occurrences of each character = {s=2, t=2, h=1, i=3}