13. JAVA, String 클래스 관련 메소드(substring, length, equals ...) & 연습문제
○ String 클래스
- 문자열과 관련된 작업에 유용한 메소드들이 포함되어 있음
- java.lang 패키지에 포함되어 제공됨
○ 자주 쓰이는 String 클래스의 메소드
String str=new String("Gone With The Wind");
ⓐ length()
- 문자열의 길이, 글자 개수
- return 값 자료형 : int
- 형식) 문자열.length()
System.out.println(str.length()); //18
ⓑ charAt()
- 해당하는 인덱스의 글자 반환
- return 값 자료형 : char
- 형식) 문자열.length(숫자)
System.out.println(str.charAt(0)); //'G' : 0번째 글자
System.out.println(str.charAt(17)); //'d' : 17번째 글자(마지막 글자)
System.out.println(str.charAt(str.length()-1)); //'d' : str의 길이 이용해서 마지막 글자 출력
ⓒ indexOf() / lastIndexOf
- 해당 문자열의 인덱스(순서값)
- indexOf는 중복되는 문자열이 있으면 가장 처음 찾은 문자열의 인덱스를 반환
- lastIndexOf는 중복되는 문자열이 있으면 가장 마지막 찾은 문자열의 인덱스를 반환
- return 값 자료형 : int
- 형식) 문자열.indexOf("문자열") / 문자열.lastIndexOf("문자열")
System.out.println(str.indexOf("G")); //0 : "G"문자열의 인덱스
System.out.println(str.indexOf("e")); //3 : 중복될 때는 처음 찾은 문자열의 인덱스
System.out.println(str.indexOf("X")); //-1 : 없는 문자열의 인덱스는 -1
System.out.println(str.lastIndexOf("i")); //15 : 중복될 때는 마지막 찾은 문자열의 인덱스
ⓓ toUpperCase() / toLowerCase()
- 문자열을 모두 대문자(toUpperCase) 또는 소문자로(toLowerCase) 변환
- return 값 자료형 : String
- 형식) 문자열.toUpperCase() / 문자열.toLowerCase()
System.out.println(str.toUpperCase()); //GONE WITH THE WIND
System.out.println(str.toLowerCase()); //gone with the wind
ⓔ replace()
- 지정한 문자를 정해준 문제로 바꿔 줌
- return 값 자료형 : String
- 형식) 문자열.replace('원래 문자', '바꿀 문자')
System.out.println(str.replace('n', 'N')); //GoNe With The WiNd
//'n' → 'N'으로 치환
ⓕ startsWith() / endsWith()
- 문자열 비교
- 해당 문자열이 지정한 문자열로 시작(startWith)하거나 끝(endsWith)나는지 확인
- return 값 자료형 : boolean
- 형식) 문자열.startsWith("비교할 문자열") / 문자열.endsWith("비교할 문자열")
System.out.println(str.startsWith("Gone")); //true (문자열이 "Gone"으로 시작하는지)
//앞에서부터 문자열 비교
System.out.println(str.endsWith("Happy")); //false (문자열이 "Happy"로 끝나는지)
//뒤에서부터 문자열 비교
ⓖ isEmpty()
- 문자열의 개수가 0인지 확인
- return 값 자료형 : boolean
- 형식) 문자열.isEmpty()
if(str.isEmpty()) {
System.out.println("빈문자열이다");
}else {
System.out.println("빈문자열이 아니다"); //"빈문자열이 아니다"
}//if end
ⓗ substring()
- 문자열 일부분만 추출(★★★)
- return 값 자료형 : String
- 끝나는 인덱스를 정해줄 때는 꼬릿말이 들어가는 공간때문에 +1해 준다
- 형식) 문자열.substring(시작인덱스) / 문자열.substring(시작인덱스, 끝인덱스+1)
System.out.println(str.substring(6)); //"ith The Wind" : 6번째~끝
System.out.println(str.substring(6, 12)); //"ith Th" : 6번째~11번째(12-1)
//첫번째 문자 추출하기
System.out.println(str.substring(0, 1));
//마지막 문자 추출하기
System.out.println(str.substring(17, 18));
System.out.println(str.substring(str.length()-1, str.length()));
System.out.println(str.substring(str.length()-1));
ⓘ equals()
- 문자열의 같고 다름을 확인
- return 값 자료형 : boolean
- 형식) 문자열.equals(비교할 문자열)
String name1="HAPPY";
String name2=new String("HAPPY");
//문자열의 내용을 비교하는 경우, equals() 함수를 이용할 것
if(name1.equals(name2)) {
System.out.println("같다");
}else{
System.out.println("다르다");
}//if end
//== 연산자 사용시, 같은 문자열임에도 "다르다" 출력
if(name1==name2) {
System.out.println("같다");
}else{
System.out.println("다르다");
}//if end
ⓙ trim()
- 문자열 좌우 끝에 있는 공백 제거
- return 값 자료형 : String
- 형식) 문자열.trim()
System.out.println("#"+" s k y ".trim() + "#"); //#s k y#
ⓚ split()
- 특정 문자를 기준으로 문자열 분리
- 분리한 뒤 배열에 차곡차곡 저장해줌
- return 값 자료형 : String[] (배열)
- 형식) 문자열.split("문자열")
String[] word=str.split("e");
for(int i=0; i<word.length; i++) {
System.out.println(word[i]);
}//for end
/*
출력결과
Gon
With Th
Wind
*/
● Practice 연습문제
Q1) 이메일 주소에 @문자가 있으면 @글자 기준으로 문자열을 분리해서 출력하고
@가 없다면 "이메일주소 틀림"메시지를 출력하시오
String email="webmaster@soldesk.com";
int at = email.indexOf("@"); //문자열이 없다면 -1 반환
if(at!=-1) {
String id=email.substring(0, at);
String server=email.substring(at+1);
System.out.println("이메일주소 맞음");
System.out.println(id); //webmaster
System.out.println(server); //soldesk.com
}else {
System.out.println("이메일주소 틀림");
}//if end
Q2) 이미지 파일만 첨부 (.png .jpg .gif)
- 파일명과 확장자명을 분리하고, 이미지 파일인지 확인
String path="d:/frontend/images/sky2022.04.06.png";
int f=path.lastIndexOf("/");
int e=path.lastIndexOf(".");
String filename=path.substring(f+1, e);
String ext=path.substring(e+1);
System.out.printf("파일명 : %s\n", filename);
System.out.printf("확장자 : %s\n", ext);
ext=ext.toLowerCase(); //확장자명을 전부 소문자로 치환
if(ext.equals("png") || ext.equals("jpg") || ext.equals("gif")) {
System.out.println("이미지 파일이 맞습니다");
}else {
System.out.println("이미지 파일이 아닙니다");
}//if end