문자열 비교
String 클래스 생성자를 사용할 때 메모리가 new 연산자에 의해 할당되기 때문에 항상 새 String 인스턴스가 생성됩니다.
그러나 문자열 리터럴은 이미 있는 것을 재사용합니다.
equals()를 사용하면 두 문자열의 내용을 비교하기 때문에 같은 결과를 얻지만 String 인스턴스의 주소를 ==와 비교하면 결과가 다르다.
1) 사용 ==
String str="HAPPY";
String name=new String("HAPPY");
if(str==name) {
System.out.println("같다");
}else {
System.out.println("다르다");
}//if end
2) equals() 사용
if(str.equals(name)) {
System.out.println("같다");
}else {
System.out.println("다르다");
}//if end
String 인스턴스에 의해 생성된 String은 읽기만 가능하고 수정할 수 없습니다.
많은 문자열 처리 작업이 필요한 경우 StringBuffer 클래스를 사용하는 것이 좋습니다. B. 문자열 간의 연결 또는 추출.
//문자열의 갯수가 0인지?
if(str.isEmpty()) {
System.out.println("빈문자열 이다");
}else {
System.out.println("빈문자열 아니다");
}//if end
//특정 문자를 기준으로 문자열 분리하기
str=new String("Gone With The Wind");
String() word=str.split(" ");
for(int i=0; i<word.length; i++) {
System.out.println(word(i));
}//if end
////////////////////////////////////////
//문자열에서 공백문자를 기준으로 분리하기
StringTokenizer st=new StringTokenizer(str, " ");
while(st.hasMoreElements()) {//토큰할 문자가 있는지?
System.out.println(st.nextToken());//토큰할 문자열 가져오기
}//while end
////////////////////////////////////////
//문자열 연산 속도
//String < StringBuffer < StringBuilder
String s1="";
System.out.println(s1.length());
s1=s1+"ONE";
System.out.println(s1.length());
s1=s1+"TWO";
System.out.println(s1.length());
s1=s1+"THREE";
System.out.println(s1.length());
System.out.println(s1);
//모든 문자열 지우기(빈 문자열 대임)
s1="";
System.out.println(s1.length());
System.out.println("#"+s1+"#");
////////////////////////////////////
StringBuilder s2=new StringBuilder();
s2.append("SEOUL");
System.out.println(s2.length() + s2.toString());
s2.append("JEJU");
System.out.println(s2.length() + s2.toString());
s2.append("BUSAN");
System.out.println(s2.length() + s2.toString());
//모든 문자열 지우기
s2.delete(0, s2.length());
System.out.println(s2.length()); //0
문자열 관련 연습
문1) 이메일 주소에 @문자 있으면
@글자 기준으로 문자열을 분리해서 출력하고
@문자 없다면 "이메일주소 틀림" 메세지를 출력하시오
출력결과
webmaster
itwill.co.kr
문2) 이미지 파일만 첨부 ( .png .jpg .gif )
출력결과
파일명 : sky2023.03.16
확장명 : jpg
– 선생님의 솔루션
(1번 문제풀이)
String email=new String("[email protected]");
//indexof - "@"값이 없다면 -1 반환
if(email.indexOf("@")==-1) {
System.out.println("이메일 주소 틀림");
}else {
System.out.println("이메일 주소 맞음");
int pos=email.indexOf("@");
System.out.println(pos);//9
//substring(), split(), StrinfTokenizer클래스
String id=email.substring(0, pos);//0,(9-1)
String server=email.substring(pos+1);//10번째부터 마지막까지
System.out.println(id);
System.out.println(server);
}//if end
(2번 문제풀이)
String path=new String("i:/frontend/images/sky2023.03.16.jpg");
//path에서 마지막 "/" 기호의 순서값
int lasrSlash=path.lastIndexOf("/");
System.out.println(lasrSlash); //18
//전체 파일명
String file=path.substring(lasrSlash+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);
//확장명을 전부 소문자로 치환 AEIOUaeiou
ext=ext.toLowerCase();
if(ext.equals("png")|| ext.equals("jpg") || ext.equals("gif")) {
System.out.println("파일이 전송되었습니다");
}else {
System.out.println("이미지 파일만 가능합니다");
}//if end
//내 풀이-substring사용
//특정 문자열 순서조회
System.out.println(path.indexOf("s"));
System.out.println(path.indexOf("6"));
System.out.println(path.indexOf("p"));
System.out.println("파일명 : " + path.substring(19,32));
System.out.println("확장명 : " + path.substring(33,36));
}//main() end
}//class end
– 내 솔루션
(1번 문제풀이)
String email=new String("[email protected]");
- substring사용
//특정 문자열 순서 조회
System.out.println(email.indexOf("@"));
System.out.println(email.indexOf("kr"));
System.out.println(email.substring(0,9));
System.out.println(email.substring(10,22));
- split사용
//특정 문자를 기준으로 문자열 분리하기
String() web=email.split("@");
for(int i=0; i<web.length; i++) {
System.out.println(web(i));
}//if end
(2번 문제풀이)
String path=new String("i:/frontend/images/sky2023.03.16.jpg");
- substring사용
//특정 문자열 순서조회
System.out.println(path.indexOf("s"));
System.out.println(path.indexOf("6"));
System.out.println(path.indexOf("p"));
System.out.println("파일명 : " + path.substring(19,32));
System.out.println("확장명 : " + path.substring(33,36));