Heestory

01.문자 찾기 본문

개발(~국비)/코테대비

01.문자 찾기

까만밀가루 2022. 10. 25. 10:32

한 개의 문자열을 입력받고, 특정 문자를 입력받아 해당 특정문자가 입력받은 문자열에 몇 개 존재하는지 코드 작성
대소문자를 구분하지 않으며 문자 길이는 100을 넘지 않는다

 

public class Test01 {

    public int solution(String str, char t){
        int answer=0;
        str=str.toUpperCase();
        t=Character.toUpperCase(t); 
        //System.out.println(str+" "+t);
		/*for(int i=0; i<str.length(); i++){
			if(str.charAt(i)==t) answer++;
		}*/
        for(char x : str.toCharArray()){
            if(x==t) answer++;
        }
        return answer;
    }

    public static void main(String[] args){
        Test01 T = new Test01();
        Scanner kb = new Scanner(System.in);
        String str=kb.next(); //입력받은 문자를 str에 저장
//        char c=str.charAt(0);
        char c=kb.next().charAt(0); //다시 입력 받은 문자의 첫번째 문자열
        System.out.print(T.solution(str, c));
    }

}

결과

더보기

apple
p
2

 


Scanner sc = new Scanner(System.in);

String일 때는 next();
byte라면 nextByte();
short라면 nextShort();
int라면 nextInt();
long이라면 nextLong();
float라면 nextFloat();
double nextDouble();

한줄로 받기 nextLine();


charAt(i)

String 타입의 데이터(문자열)에서 i번째 특정 문자를 char 타입으로 변환할 때 사용하는 함수


toUpperCase(), toLowerCase()

- toUpperCase() : 문자를 대문자로 바꿔줌
- toLowerCase() : 문자를 소문자로 바꿔줌

단 문자열의 경우 문자열 또는 문자열 뒤에 toUpperCase
문자의 경우 Character 클래스의 toUpperCase에 변환할 문자를 파라미터로 넣어 선언

        String Str = "hello";
        str=str.toUpperCase();
        
        char t;
        t=Character.toUpperCase(c);

toCharArray()


문자열을 char형 배열로 바꿔준다. 반환되는 배열의 길이는 문자열의 길이와 같다.
주의 문자열의 공백 또한 인덱스에 포함한다.

'개발(~국비) > 코테대비' 카테고리의 다른 글

10.가장 짧은 문자 거리 / 11.문자열 압축  (0) 2022.11.03
08.replaceAll(정규식 이용) / 09.숫자만 추출  (0) 2022.11.02
07.회문 문자열  (0) 2022.11.01
06.중복 제거  (0) 2022.11.01
05.특정 문자 뒤집기  (0) 2022.11.01