프로그래머스/LV1.자바
자바 메소드&문법정리
몰라닉네임
2022. 10. 26. 15:59
- toLowerCase() 문자열을 소문자로 변환한다.
- toUpperCase() 문자열을 대문자로 변환한다.
- String.toCharArray(); 문자열을 한 글자씩 잘라서 이를 char 타입의 배열에 집어넣어주는 메소드이다.
String Str = "do not KNOW WHAT";
System.out.println(str, toLowerCase()); //소문자로
ex)
프로그래머스 문자열 내 p와 y의 개수 (방법1)
/*문자열을 하나씩 잘라서 배열로 만들고 그 배열들을 배열 길이만큼 그게 p 또는 s와 같은지 비교
*/
class Solution {
boolean solution(String s) {
boolean answer = true;
s = s.toLowerCase();
char[] charList = s.toCharArray();
int cntp=0;
int cnty=0;
for(int i=0; i<charList.length; i++){
if(charList[i] == 'p'){
cntp++;
}
else if(charList[i] == 'y' ){
cnty++;
}
}
if (cntp == cnty){
answer = true;
}
else {
answer = false;
}
return answer;
}
}
.
- split은 구분자를 기준으로 문자열을 잘라 배열로 입력할 때 사용하는 메소드이다.
ex)
프로그래머스 문자열 내 p와 y의 개수 (방법2)
class Solution {
boolean solution(String s) {
boolean answer = true;
int pcnt = 0;
int ycnt = 0;
String[] array = s.toLowerCase().split(""); // 소문자로 바꿔서 잘라서 배열에 넣음
for (int i = 0; i < array.length; i++) { //for문 돌리면서 p 와 y cnt 세기
if ("p".equals(array[i])) {
pcnt++;
} else if ("y".equals(array[i])) {
ycnt++;
}
}
if (pcnt != ycnt) {
answer = false;
}
else{
answer = true;
}
return answer;
}
}
- Integer.parseInt(str) 전달받은 문자열을 int로 변환한다.
ex) 프로그래머스 문자열을 정수로 바꾸기
class Solution {
public int solution(String s) {
int answer = 0;
// String str = "" + n; // 문자열 + 숫자 = 문자열 long 크기의 배열 만들기 힘드니깐
answer = Integer.parseInt(s);
return answer;
}
}
+ 프로그래머스 자연수 뒤집어 배열로 만들기 문제
long n ;
String str = "" +n; //문자열 + 숫자 = 문자열
class Solution {
public int[] solution(long n) {
String str = "" + n; // 문자열 + 숫자 = 문자열 long 크기의 배열 만들기 힘드니깐
int[] answer = new int[str.length()];
int idx = 0;
while(n>0){
// 3) 123 % 10 = 3
// 4) 12 % 10 = 2
// 5) 1 % 10 = 1
answer[idx] = (int)(n%10);
// 123 = 12
// 12 = 1
// 1 = 0 ( 0.1 )
n=n/10;
idx++;
}
return answer;
}
}