본문 바로가기

IT/Java

20_Java String 클래스

String 클래스와 StringTokenizer 클래스가 가진 유용한 메소드 몇 가지를 정리해보려고 한다.

 

01. String 클래스 - charAt(index) 메소드

해당 문자열의 index가 나타내는 문자를 찾아준다.

 

예를 들어 주민등록번호를 숫자로만 입력했을 때, 7번째 자리의 숫자는 성별을 나타낸다.

charAt(index) 메소드를 사용하면 해당 주민등록번호를 가진 사람의 성별을 알 수 있다.

주의할 점은, 배열과 마찬가지로 문자열의 인덱스도 0번부터 시작한다는 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package ex05_string;
 
import java.util.Scanner;
 
public class StringCharAtExample {
    // 주민등록번호에서 남자와 여자 구분
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("주민등록번호 입력 ( - 제외) >>");
        String ssn = sc.nextLine();
        char sex = ssn.charAt(6);
 
        switch (sex) {
        case '1':
        case '3':
            System.out.println("남자입니다.");
            break;
        case '2':
        case '4':
            System.out.println("여자입니다.");
            break;
        default :
            System.out.println("잘못 입력하셨습니다.");
        }
        
        sc.close();
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

02. String 클래스 - indexOf("문자열") 메소드

 

charAt(index)와 반대로, 문자열로 검색하여 해당 인덱스번호를 리턴해주는 메소드이다.

당연히 인덱스번호는 0부터 시작이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class StringIndexOfExample {
    public static void main(String[] args) {
        String model = "bugatti chiron";
        
        int location = model.indexOf("r");
        System.out.println("location of [r] : " + location);    //공백도 인덱스에 포함된다.
        location = model.indexOf("i");
        System.out.println("location of [i] : " + location);    //같은 문자가 여러개면 가장 앞에 있는 것의 인덱스가 리턴 된다.
        System.out.println("length : " + model.length());    //공백도 길이에 포함 된다.
        
        //문자열을 검색하면 첫번째 인덱스가 리턴된다.
        System.out.println("location of 'chiron' : " + model.indexOf("chiron")); 
        
        if(model.indexOf("chiron"== -1) {    //존재하지 않는 인덱스번호(즉, chiron이라는 문자열이 없다면)
            System.out.println("chiron이 아니네!");
        }else {
            System.out.println("chiron이네!");
        }
        
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

03. String 클래스 - replace("원본문자열", "대체할 문자열") 메소드

원본 문자열의 특정 문자들을 다른 하나의 문자로 바꾸고 싶을 때 사용한다.

아래의 예시는 문장의 띄어쓰기를 언더바(_) 기호로 바꾼 후,

문자열 하나를 공백으로 대체(즉, 삭제) 한 것이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package ex05_string;
 
public class StringReplaceExample {
    public static void main(String[] args) {
        String str1 = "Le cose non sono sempre come sembrano";
        String str2 = str1.replace(' ''_');
        System.out.println("str1 : " + str1);    
        
        //실행해보면 알겠지만 replace를 실행했다고 원본이 바뀌는 것은 아니다.
        str2.replace("_sempre""");
        System.out.println("str2 : " + str2);
        
        //따라서 새로운 문자열을 사용하기 위해서는 새로운 변수에 대입해줘야 한다.
        String str3 = str2.replace("_sempre",  "");
        System.out.println("str3 : " + str3);
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
cs

 

실행결과이다.

04. String 클래스 - substring() 메소드

substring 메소드는 매개변수에 따라 두 가지로 나눌 수 있다.

>> substring(시작인덱스, 끝 인덱스);  - 예) str.substring(0, 3) : 0번 이상 3번 미만 인덱스 만큼 자른다

>> substring(시작인덱스); - 예) str.substring(5) : 5번 인덱스 부터 모두 자른다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package ex05_string;
 
public class StringSubstringExample {
    public static void main(String[] args) {
        String ssn = "901218-2345678";
        
        String firstNum = ssn.substring(06);
        System.out.println(firstNum);
        
        String secondNum = ssn.substring(7);
        System.out.println(secondNum);
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

05. String 클래스 - trim() 메소드

 

trim() 메소드는 문자열 앞 뒤의 공백을 없애준다.

문자열 내부에 있는 공백은 trim 메소드로 제거할 수 없다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package ex05_string;
 
public class StringTrimExample {
    public static void main(String[] args) {
        String tel1 = "   02";
        String tel2 = "123   ";
        String tel3  ="    1234    ";
        
        String tel = tel1.trim() + tel2.trim() + tel3.trim();
        System.out.println(tel);
        
        //문자열 사이의 공백은 제거하지 못한다.
        String str= "    12  34".trim();
        System.out.println(str);
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter