본문 바로가기
Java/Coding-Test

[Java] 1-1 문자찾기

by JS1111 2022. 1. 4.

문제

한 개의 문자열을 입력받고, 특정 문자를 입력받아 해당 특정문자가 입력받은 문자열에 몇 개 존재하는지 알아내는 프로그램을 작성하세요.
대소문자를 구분하지 않습니다.문자열의 길이는 100을 넘지 않습니다.

입력

첫 줄에 문자열이 주어지고, 두 번째 줄에 문자가 주어진다.
문자열은 영어 알파벳으로만 구성되어 있습니다.

출력

첫 줄에 해당 문자의 개수를 출력한다.

예시 입력

Computercooler  
c

예시 출력

2

출처

인프런 - 자바-알고리즘-문제풀이-코테대비

내 풀이

private static int stringSearchByLoop(String str, char ch) {
    int result = 0;
    int index = 0;
    while(str.indexOf(ch, index) >= 0) {
        index = str.indexOf(ch, index) + 1;
        result++;
    }
    return result;
}

private static int stringSearchByLoop2(String str, char ch) {
    int result = 0;
    for (char c : str.toCharArray()) {
        if (c == ch) result++;
    }

    return result;
}

private static int stringSearchByStream(String str, char ch) {
    return (int) str.chars().filter(c -> c == ch).count();
}

기억할 점

String클래스 chars() vs codePoints()

chars()는 단순히 16bit씩 스트림을 만든다
codePoints() 는 high-surrogate를 만나면 뒤의 low-surrogate와 합쳐서 스트림을 만든다


Scanner클래스 next() vs nextLine()

next(), nextInt()는 분리자(' ', \r, \f, \n)를 기준으로 하나의 값을 받는다
nextLine()은 \n까지 읽고 \n을 제외한 값을 받는다

nextInt()이후에 바로 nextLine()을 사용하면 버퍼에 남아있는 \n을 읽어서 str에 \n만 저장된다
중간에 nextLine()을 사용하여 방지할 수 있다

'Java > Coding-Test' 카테고리의 다른 글

[Java] 1-9 숫자만 추출  (0) 2022.01.15
[Java] 1-8 유효한 팰린드롬  (0) 2022.01.15
[Java] 1-7 회문 문자열  (0) 2022.01.14
[Java] 1-6 중복문자제거  (0) 2022.01.13
[Java] 1-3 문장 속 단어  (0) 2022.01.08

댓글