GitHub

https://github.com/Choidongjun0830

Java

[Java] String에서 char/String 개수 구하기

gogi masidda 2023. 8. 13. 12:53
package com.collection;

import java.util.HashMap;
import java.util.Map;

public class MapRunner {
    public static void main(String[] args){
        String str = "This is an awesome occasion." +  "This has never happend before.";

        Map<Character,Integer> occurances = new HashMap<>();

        char[] characters = str.toCharArray(); //String을 char로 쪼개서 배열에 넣기
        for(char character:characters) {
            Integer integer = occurances.get(character); //Map에서 key값으로 value 가져오기
             if(integer == null){ // value값이 없으면
                 occurances.put(character,1);
             } else {
                 occurances.put(character,integer+1);
             }
        }

        System.out.println(occurances);
        //{ =8, a=5, b=1, c=2, d=1, e=7, f=1, h=4, i=4, m=1, n=4, .=2, o=4, p=2, r=2, s=6, T=2, v=1, w=1}
        
        Map<String,Integer> stringOccurances = new HashMap<>();

        String[] words = str.split(" ");

        for(String word:words) {
            Integer integer = stringOccurances.get(word); //Map에서 key값으로 value 가져오기
            if(integer == null){ // value값이 없으면
                stringOccurances.put(word,1);
            } else {
                stringOccurances.put(word,integer+1);
            }
        }

        System.out.println(stringOccurances);
        // {awesome=1, never=1, before.=1, This=1, is=1, has=1, occasion.This=1, an=1, happend=1}
    }
}
728x90