티스토리 뷰

프로그래밍/Java

String 클래스

안싱미 2016. 1. 29. 10:58

String클래스에서 자주 쓰이는 메서드

 메서드

 예제

 결과

boolean equals(Object obj)

매개변수로 받은 문자열(obj)과 String 인스턴스의 문자열을 비교한다. obj가 String이 아니거나 문자열이 다르면 false를 반환다.

String s = "Hello";
boolean b1 = s.equals("Hello");
boolean b2 = s.equals("hello");

b1 = true
b2 = false

boolean equalsIgnoreCase(String str)

문자열과 String인스턴스의 문자열을 대소문자 구분없이 비교한다.

String s = "Hello";
boolean b1 = s.equalsIgnoreCase("HELLO");
boolean b2 = s.equalsIgnoreCase("heLLo");

b1 = true
b2 = true

int indexOf(int ch)

주어진 문자(ch)가 문자열에 존재하는지 확인하여 위치(index)를 알려준다. 못찾으면 -1을 반환한다. (index는 0부터 시작)

String s = "hello";
int index1 = s.indexOf('o');
int index2 = s.indexOf('k');

index1 = 4
index2 = -1

int lastIndexOf(int ch)

지정된 문자 또는 문자코드를 문자열의 오른쪽 끝에서부터 찾아서 위치(index)를 알려준다. 못찾으면 -1을 반환한다.

String s = "java.lang.Object";
int index1 = s.lastIndexOf('.');
int index2 = s.indexOf('.');

index1 = 9
index2 = 4

String[] split(String regex)

문자열을 지정된 분리자(regex)로 나누어 문자열을 배열에 담아 반환한다.

String animals = "dog,cat,bear";
String[] arr = animal.split(",");

arr[0] = "dog";
arr[1] = "cat";
arr[2] = "bear";

String substring(int begin)

String substring(int begin, int end)

주어진 시작위치(begin)부터 끝 위치(end)범위에 포함된 문자열을 얻는다. 이 때, 시작 위치의 문자는 범위에 포함되지만, 끝 위치의 문자는 포함되지 않는다.
(begin <= x < end)

String s = "java.lang.Object";
String c =  s.substring(10);
String p = s.substring(5,9);

c = "Object"
p = "lang"

String trim()

문자열의 왼쪽 끝과 오른쪽 끝에 있는 공백을 없앤 결과를 반환한다. 이때 문자열 중간에 있는 공백은 제거되지 않는다.

String s = "   Hello World   ";
String s1 = s.trim();

s1 = "Hello World"


실습 예제

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 
package com.ktds.smahn;
 
public class SubstringTest {
    
    private void start(){
        
        String welcome = "Hello, World!";
        System.out.println(welcome);
        System.out.println(welcome.length());
        
        // .substring(시작index, 끝index) 
        // 직접 입력하는 방식
        String world = welcome.substring(713);
        
        // .indexOf : 공백이 있는 인덱스를 알려준다.
        // 공백 다음부터 끝까지 가지고 온다.
        world = welcome.substring(welcome.indexOf(" "+ 1, welcome.length());
        System.out.println(world);
        
        // 끝 index를 안쓰면 자동으로 끝까지 체크한다.
        world = welcome.substring(welcome.indexOf(" "+ 1);
        System.out.println(world);
        
        // hello의 길이까지 출력
        String hello = welcome.substring(0, welcome.indexOf(","));
        hello = welcome.substring(0"hello".length());
        System.out.println(hello);
        
        // 4부터 8번 인덱스까지 출력
        String str = welcome.substring(48);
        System.out.println(str);
        
        // o부터 끝까지
        str = welcome.substring( welcome.indexOf("o") );
        System.out.println(str);
        
        // 마지막 o부터 끝까지
        str = welcome.substring( welcome.lastIndexOf("o") );
        System.out.println(str);
        
        String id = welcome.substring(03);
        System.out.println(id);
        forint i = 0; i < 5; i++){
            // 글자수를 알면 해킹이 가능하기 때문에... 0 에서 5를 일반적으로 한다.
            id += "*";
        }
        System.out.println(id);
 
 
    }
    
    public static void main(String[] args) {
        
        SubstringTest substringTest = new SubstringTest();
        substringTest.start();
        
    }
 
}
 
cs


'프로그래밍 > Java' 카테고리의 다른 글

사이냅소프트 면접문제  (0) 2016.05.01
재귀호출  (0) 2016.03.17
대출 이자 계산기  (0) 2016.01.28
날짜 구하기  (0) 2016.01.28
[Java 종합실습문제] 자전거 대여점  (0) 2016.01.28
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 30 31
글 보관함