본문 바로가기
Backend/JAVA

[JAVA] String

by howdyoon 2023. 3. 16.

문자열의 비교

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인스턴스가 갖고 있는 문자열은 읽어 올 수만 있고 변경할 수는 없다.

문자열 간의 결합이나 추출등 문자열을 다루는 작업이 많이 필요할 경우 StringBuffer클래스를 사용하는 것이 좋다.

//문자열의 갯수가 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

 

String 관련 연습문제

문1) 이메일 주소에 @문자 있으면
  @글자 기준으로 문자열을 분리해서 출력하고
  @문자 없다면 "이메일주소 틀림" 메세지를 출력하시오        

  출력결과
  webmaster
  itwill.co.kr
  
문2) 이미지 파일만 첨부 ( .png .jpg .gif )

    출력결과
    파일명 : sky2023.03.16
    확장명 : jpg

- 강사님 풀이

[1번 문제풀이]
String email=new String("webmaster@itwill.co.kr");

//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("webmaster@itwill.co.kr");

- 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));

'Backend > JAVA' 카테고리의 다른 글

[JAVA] static  (0) 2023.03.16
[JAVA] this와 this()  (0) 2023.03.16
[JAVA] constructor  (0) 2023.03.15
[JAVA] class  (0) 2023.03.15
[JAVA] main  (0) 2023.03.15