String 클래스
String클래스에서 자주 쓰이는 메서드
메서드 | 예제 | 결과 |
boolean equals(Object obj) 매개변수로 받은 문자열(obj)과 String 인스턴스의 문자열을 비교한다. obj가 String이 아니거나 문자열이 다르면 false를 반환다. |
String s = "Hello"; |
b1 = true |
boolean equalsIgnoreCase(String str) 문자열과 String인스턴스의 문자열을 대소문자 구분없이 비교한다. | String s = "Hello"; | b1 = true |
int indexOf(int ch) 주어진 문자(ch)가 문자열에 존재하는지 확인하여 위치(index)를 알려준다. 못찾으면 -1을 반환한다. (index는 0부터 시작) | String s = "hello"; | index1 = 4 |
int lastIndexOf(int ch) 지정된 문자 또는 문자코드를 문자열의 오른쪽 끝에서부터 찾아서 위치(index)를 알려준다. 못찾으면 -1을 반환한다. | String s = "java.lang.Object"; | index1 = 9 |
String[] split(String regex) 문자열을 지정된 분리자(regex)로 나누어 문자열을 배열에 담아 반환한다. | String animals = "dog,cat,bear"; | arr[0] = "dog"; |
String substring(int begin) String substring(int begin, int end) 주어진 시작위치(begin)부터 끝 위치(end)범위에 포함된 문자열을 얻는다. 이 때, 시작 위치의 문자는 범위에 포함되지만, 끝 위치의 문자는 포함되지 않는다. | String s = "java.lang.Object"; | c = "Object" |
String trim() 문자열의 왼쪽 끝과 오른쪽 끝에 있는 공백을 없앤 결과를 반환한다. 이때 문자열 중간에 있는 공백은 제거되지 않는다. | String s = " Hello World "; | 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(7, 13);
// .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(4, 8);
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(0, 3);
System.out.println(id);
for( int 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 |