[ 프로그래머스 ] #72410 : 신규 아이디 추천 - JAVA

🔗 신규 아이디 추천

class Solution {
public String solution(String new_id) {
// 3~15자 이하
// 알파벳 소문자, 숫자, -, _, . 가능
// 7 단계 아이디 규칙 검사, 맞지 않는 경우 새로운 아이디 추천
// new_id : 신규 유저가 입력한 아이디
// 1. 대문자 -> 소문자
new_id=new_id.toLowerCase();
// 2. 가능한 문자 제외 삭제
new_id = new_id.replaceAll("[^0-9a-z._-]", "");
// 3. .연속을 . 하나로
new_id = new_id.replaceAll("[.]{2,}", ".");
// 4. . 양끝에 있는거 제거
new_id=trimDot(new_id);
// 5. 빈 문자열이면 "a" 대입
if(new_id.isEmpty())new_id+="a";
// 6. 길이가 16 이상이면 첫15개의 문자만 가져감
if(new_id.length()>=16)new_id=new_id.substring(0,15);
// 7. 제거 후 . 양 끝 제거
new_id=trimDot(new_id);
// 8. 길이가 2자 이하면 마지막 문자를 길이가 3 될 때까지 뒤에 붙임
char lastLetter=new_id.charAt(new_id.length()-1);
while(new_id.length()<3){
new_id+=lastLetter;
}
return new_id;
}
private String trimDot(String new_id){
if(new_id.startsWith("."))new_id=new_id.substring(1);
if(new_id.endsWith("."))new_id=new_id.substring(0,new_id.length()-1);
return new_id;
}
}