Post

String_문자 찾기_charAt, indexOf

✅ 한 개의 문자열을 입력받아 특정 문자가 입력받은 문자열에 몇 개 존재하는지 알아내기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Scanner;

class Main {
    public int solution(String str, char t){
        int answer=0;
        t= Character.toUpperCase(t);
        str= str.toUpperCase();
        //for문
        for(int i=0; i<str.length(); i++){
            if( t== str.charAt(i)){
                answer++;
            }
        }
        //forEach
        for(char x: str.toCharArray(t)){
            if( x == t){
            answer++;
        }
        return answer;
    }
    public static void main(String[] args){
        Main T = new Main();
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        char c=  sc.next().charAt(0);
        System.out.println(T.solution(str, c));
    }

}

//⭐️input:
//Computercooler
//c
//⭐️output:
//2

🔴 TroubleShooting

처음에 MainOne으로 class명을 만들어서 MainOne T = new MainOne();으로 했다가 문제 제출할 때만 class명을 Main으로 바꿨더니 compile error이 발생했다. 클래스 이름을 바꿔주니 문제가 해결되었다.

🔵 ThingsILearned

✔️ 새로운 함수를 만들고 psvm안에서 사용하려면 클래스 불러와야 한다.

그래서 solution함수를 사용하기 위해 psvm에서 Main T = new Main(); 코드를 작성하였다.

✔️ charAt 🆚 indexOf

charAt returns the char value at the specified index
whereas indexOf returns the index within this string of the first occurrence of the specified character.

✔️ toCharArray()

하나의 char을 배열로 바꿔서 하나하나 불러온다.
그냥 for(char x: str)하면 안 됨! 반드시 array로 바꿔서

This post is licensed under CC BY 4.0 by the author.