본문 바로가기
프로그래머 ,백준, 유튜브, 문제

문자열 내 p와 y의 개수_프로그래머스

by 리승우 2022. 9. 23.

[필요개념]

> String을 char로 나눈 뒤 배열에 담는 꿀팁

> == 과 equals의 차이점

> 왜 어떤 곳에선 ==이고 어떤 곳에서는 equals일까?

public class Hello {

    public static void main(String[] args) {
    boolean answer = true;
    String s = "pPoooyY";

    //소문자 변경 후, split함수로 단어마다 나눈 뒤 배열에 담음
    String[] arr = s.toLowerCase().split("");
    System.out.println(arr[0]); //출력값 p


    int p_count =0;
    int y_count =0;

    // 배열의 크기에 맞게 for문을 돌며 p 혹은 y와 같은 것이 있을 시 각자의
    // count에 맞게 숫자를 증가시킴
    // == 과 equals의 차이는 알아두어야함!!
    // 주소 <-> 값 그 자체
    for(int i=0; i<arr.length; i++){
        if(arr[i].equals("p")){
            p_count++;
        } else if(arr[i].equals("y")){
            y_count++;
        }
    }
    
    if(p_count == y_count){
        answer = true;
    } else{
        answer = false;
    }

    }
}

댓글