230327 데일리코딩

허크·2023년 3월 27일
0

문자열 내부 연속된 홀수


split()

if(str.length() == 0) {
	return null;
}
// 문자열을 배열로 담아줌
String[] nums = str.split("");
String result = new String();
// 반복문으로 문자열을 순회
for (int i = 0; i < str.length() - 1; i++) {
	// i와 i+1이 모두 홀수 일 경우
	int check1 = Integer.parseInt(nums[i]) % 2;
	int check2 = Integer.parseInt(nums[i+1]) % 2;
	if(check1 != 0 && check2 != 0) {
		// i뒤에 '-'를 추가해줌
		nums[i] = nums[i].concat("-");
	}
}
result = String.join("", nums);
return result;
  • 원하는 결과값은 나오지만 굳이 문자열을 분리하고 배열로 생성하고 다시 새 배열에 담는 등 불필요한 작업이 감지됨



charAt()

if(str.length() == 0) {
	return null;
}
// 결과값을 담을 result 선언 후 첫값을 담아줌
String result = "" + str.charAt(0);
// 반복문으로 순회하면서
for (int i = 1; i < str.length(); i++) {
	int check1 = Character.getNumericValue(str.charAt(i - 1)) % 2;
	int check2 = Character.getNumericValue(str.charAt(i)) % 2;
	// 둘다 홀수면 "-"을 추가
	if(check1 != 0 && check2 != 0) {
		result = result + "-";
	}
	// 결과값에 현요소를 추가
	result = result + str.charAt(i);
}
return result;
  • char타입을 바로 String으로 선언하면 컴파일 에러가 나므로 "" + 해줌
  • Character.getNumericValue vs Integer.parseInt

    • 전자는 char 타입을 매개변수로 받아서 int 타입으로 반환

    • 후자는 String 타입을 매개변수로 받아서 int 타입으로 반환

    • 예를들어 "12"를 Character.getNumericValue에 넣으면 에러가 발생하므로 Integer.parseInt를 사용해야한다

profile
codestates seb 44th // 다크모드로 보는걸 추천드립니다

0개의 댓글