코딩테스트

[인프런 자바 알고리즘 문제풀이] 1. 문자 찾기

셩리둥절 2022. 9. 19. 17:33
반응형

한 개의 문자열, 한 개의 문자를 입력 받아 문자열에 몇 개 존재하는지 알아내는 프로그램

대소문자 구별X, 문자열의 길이는 100을 넘지 않는다.

이런식으로 작성하였는데 출력 양식을 지키지 않아서 오답 나왔다.

그래서 밑에처럼 다시 수정했다.

import java.util.Locale;
import java.util.Scanner;

public class Main {
    public int solution(String str, char ch) {
        int answer = 0;
        str = str.toUpperCase(Locale.ROOT);
        ch = Character.toUpperCase(ch);
        for(int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == ch) {
                answer++;
            }
        }

        return answer;
    }

    public static void main(String[] args) {
        Main C = new Main();
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        char ch = sc.next().charAt(0);
        int count = 0;
        System.out.println(C.solution(str, ch));

    }
}

성공!

향상된 for 문 사용하기

import java.util.Locale;
import java.util.Scanner;

public class Main {
    public int solution(String str, char ch) {
        int answer = 0;
        str = str.toUpperCase(Locale.ROOT);
        ch = Character.toUpperCase(ch);
        for(char i : str.toCharArray()) {
            if(i == ch) {
                answer++;
            }
        }

        return answer;
    }

    public static void main(String[] args) {
        Main C = new Main();
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        char ch = sc.next().charAt(0);
        int count = 0;
        System.out.println(C.solution(str, ch));

    }
}

toCharArray() 함수를 사용하여 배열 형태로 바꾸어준다!

문자열에 success를 입력시 배열에는 index마다

index char
0 s
1 u
2 c
3 c
4 e
5 s
6 s

요런식으로 들어가게된다.

 

문장 입력시

import java.util.Locale;
import java.util.Scanner;

public class Main {
    public int solution(String str, char ch) {
        int answer = 0;
        String str2 = "";
        str = str.toUpperCase(Locale.ROOT);
        ch = Character.toUpperCase(ch);
        for(char i : str.toCharArray()) {
            if(i == ch) {
                answer++;
            }
        System.out.println(i);
        }

        return answer;
    }

    public static void main(String[] args) {
        Main C = new Main();
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char ch = sc.next().charAt(0);
        System.out.println(C.solution(str, ch));

    }
}

String str = sc.next()에서 sc.nextLine()으로 변경되었다.

next()는 개행문자를 건너뛰고 nextLine()은 개행문자를 포함한다

next() VS nextLine() 예시

1) next() 이용

이런식으로 i'm good을 입력후 enter를 입력 시

i'm 뒤에 공백이 들어가 무시되어 문자(ch)는 개행문자를 제외한 g가 되어버린다.

버퍼에 쌓이는 개념이여서 뒤의 'ood'는 강제로 잘려버린다

2) nextLine() 이용(solution 메소드 동일)

I'm Kim으로 입력시

index char
0 I
1 '
2 m
3  
4 K
5 i
6 m

이런식으로 공백도 들어가니 유념해야한다.

 

문자열 길이에 대한 부분이 안들어갔는데

for문을 돌리기 전에 밑의 조건을 확인하는 것을 추가해야겠다.

if(str.length() > 100) {
	System.out.println("문자열의 최대 길이는 100 이하로 입력해주세요.");
}

next(), nextLine()에 대하여 좋은 블로그글 링크

https://devlog-wjdrbs96.tistory.com/80

 

 

 

 

반응형