1. 문자 찾기
한 개의 문자열을 입력받고, 특정 문자를 입력받아 해당 특정문자가 입력받은 문자열에 몇 개 존재하는지 알아내려고 한다. 단, 문자열은 영어 알파벳으로만 구성되어 있고 대소문자를 구분하지 않는다.
방법1. 인덱스값으로 접근 CharAt()
* CharAt(index) : 문장중에 인덱스 위치에 해당되는 문자 추출
import java.util.*;
public class Main {
public static int solution(String str, char c){
int answer=0;
str=str.toUpperCase();
c=Character.toUpperCase(c);
for(int i=0; i<str.length(); i++){
if(str.charAt(i)==c) answer++;
}
return answer;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.next();
char c= sc.next().charAt(0);
System.out.println(solution(str,c));
}
}
방법2. 문자열을 문자배열로 생성 String.toCharArray()
* String.toCharArray() : 문자열을 한 글자씩 쪼개서 이를 char타입의 배열에 집어넣어주는 메소드
import java.util.*;
public class Main {
public static int solution(String str, char c){
int answer=0;
str=str.toUpperCase();
c=Character.toUpperCase(c);
for(char x : str.toCharArray()){
if(x==c) answer++;
}
return answer;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.next();
char c= sc.next().charAt(0);
System.out.println(solution(str,c));
}
}
입력받은 문자열과 문자를 모두 소문자/대문자로 변경 한 뒤 문자를 하나씩 비교해 입력한 문자와 일치하는 문자를 발견하면 answer에 1을 더해준다.
[인프런 학습 강의 사이트]
자바(Java) 알고리즘 문제풀이 : 코딩테스트 대비 - 인프런 | 강의
자바(Java)로 코딩테스트를 준비하시는 분을 위한 강좌입니다. 코딩테스트에서 가장 많이 출제되는 Top 10 Topic을 다루고 있습니다. 주제와 연동하여 기초문제부터 중급문제까지 단계적으로 구성
www.inflearn.com
'알고리즘 > 알고리즘 정리' 카테고리의 다른 글
[문자열(String) 알고리즘] 6. 중복문자제거 (0) | 2021.07.29 |
---|---|
[문자열(String) 알고리즘] 5. 특정 문자 뒤집기 (0) | 2021.07.28 |
[문자열(String) 알고리즘] 4. 단어 뒤집기 (0) | 2021.07.28 |
[문자열(String) 알고리즘] 3. 문장 속 단어 (0) | 2021.07.28 |
[문자열(String) 알고리즘] 2. 대소문자 변환 (0) | 2021.07.28 |