String.replaceAll
메서드로 정규식을 조합하면 쉽게 풀 수 있는 문제이다. // 메서드를 분리하지 않은 채로 구현하는 게 더 나을것 같은 코드...
static String recommendId(String id) {
id = step1(id);
id = step2(id);
id = step3(id);
id = step4(id);
id = step5(id);
id = step6(id);
id = step7(id);
return id;
}
아래의 코드는 프로그래머스 내의
다른 사람의 풀이
를 참고했습니다.
public class NewIdRecommend {
public static void main(String[] args) {
String id = "...!@BaT#*..y.abcdefghijklm";
RecommendId recommendId = new RecommendId(id)
.step1()
.step2()
.step3()
.step4()
.step5()
.step6()
.step7();
System.out.println(recommendId.getId());
}
private static class RecommendId {
private String id;
private RecommendId(String id) {
this.id = id;
}
// 대문자를 소문자로
private RecommendId step1() {
id = id.toLowerCase();
return this;
}
//`알파벳`,`숫자`,`-`,`_`,`.`를 제외한 모든 문자는 삭제
private RecommendId step2() {
id = id.replaceAll("[^a-z0-9-_.]","");
return this;
}
// 마침표가 2번 연속 있는 경우 마침표 하나로 변경
private RecommendId step3() {
id= id.replaceAll("[.]{2,}",".");
return this;
}
// 첫 문자가 마침표라면 삭제
private RecommendId step4() {
if(id.charAt(0) == '.') {
id = id.substring(1);
}
return this;
}
// 문자열이 비어있다면 a 삽입
private RecommendId step5() {
if(id.isEmpty()) {
id+= "a";
}
return this;
}
// 문자열 길이를 15 이하로, 마지막 문자가 마침표면 삭제
private RecommendId step6() {
if(id.length() > 15) {
id = id.substring(0,15);
}
// 정규식으로 마침표 제거
// id = id.replaceAll("[.]$","");
//substring으로 마침표 제거
int index = id.length()-1;
if(id.charAt(index)=='.') {
id =id.substring(0,index);
}
return this;
}
// 문자열이 2이하면 마지막 문자를 문자열 길이가 3이될때까지 추가
private RecommendId step7() {
int lastIndex = id.length()-1;
while(id.length() < 3) {
id += id.charAt(lastIndex);
}
return this;
}
private String getId() {
return id;
}
}