웹개발 교육/Java
[32일] Java (22) - String 연습 문제
ewok
2022. 9. 8. 17:51
문제 1
//문1) 이메일 주소에 @문자 있으면
// @글자 기준으로 문자열을 분리해서 출력하고
// @문자 없다면 "이메일주소 틀림" 메세지를 출력하시오
/*
출력결과
webmaster
itwill.co.kr
*/
String email = new String("webmaster@itwill.co.kr");
//내 풀이
if(email.indexOf("@")!=-1) {
String[] word = email.split("@");
for(int i=0; i<word.length; i++) {
System.out.println(word[i]);
}//for end
} else {
System.out.println("이메일 주소 틀림");
}//if end
//다른 풀이
if(email.indexOf("@")==-1) {
System.out.println("이메일 주소 틀림");
} else {
System.out.println("이메일 주소 맞음");
int pos = email.indexOf("@");
//System.out.println(pos); //9
String id = email.substring(0, pos);
String server = email.substring(pos+1);
System.out.println(id);
System.out.println(server);
}//if end
문제 2
//문2) 이미지 파일만 첨부 (.png .jpg .gif)
/*
출력결과
파일명 : sky2022.09.08
확장명 : png
*/
String path = new String("i:/frontend/images/sky2022.09.08.png");
//내 풀이
path = path.toLowerCase(); //확장자 대소문자 상관없도록
if(path.indexOf("png")!=-1 || path.indexOf("jpg")!=-1 || path.indexOf("gif")!=-1) {
System.out.println("파일명 : " + path.substring(path.lastIndexOf("/")+1, path.lastIndexOf(".")));
System.out.println("확장명 : " + path.substring(path.lastIndexOf(".")+1));
}//if end
//다른 풀이
//마지막 "/" 기호의 순서값
int lastSlash = path.lastIndexOf("/");
System.out.println(lastSlash); //18
//전체 파일명
String file = path.substring(lastSlash+1);
System.out.println("전체 파일명 : " + file);
//file에서 마지막 "." 기호의 순서값
int lastDot = file.lastIndexOf(".");
System.out.println(lastDot); //13
//파일명
String filename = file.substring(0, lastDot);
System.out.println("파일명 : " + filename);
//확장명
String ext = file.substring(lastDot+1);
System.out.println("확장명 : " + ext);