String class

String 생성

1
String str1 = "abc";
cs

1
String str = new String("abc");
cs

: 문자열 "abc"는 문자열 리터럴로 절대 바뀌지 않는다. 만약 문자열을 자르거나 다른 문자열과 연결한다는 것은 "abc"가 바뀌는 것이 아니라 메모리를 새로 할당 받아 새로운 문자열 리터럴을 생성하는 것이다. 또 동일한 문자열 리터럴을 여러 String 객체에 할당한다면 동일한 리터럴을 같이 사용하는 것이다.


1
2
String a = "abc";
String b = "abc";
cs


  위의 코드의 a, b는 동일한 메모리에 있는 리터럴을 사용하는 것이며 a, b에서 문자열을 변경해도 "abc" 자체는 변경되지 않고 변경된 형태의 새로운 문자열 리터럴이 생성되는 것이기 때문에 a, b는 서로 영향을 주지 않는다.



String과 Number의 변환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//숫자형태의 문자열을 그 타입의 숫자로 변환한다.
int i = Integer.valueOf("123").intValue();
float f = Float.valueOf("23.5").floatValue();
 
//문자열을 숫자로 변환하는 메서드, 파라미터로 받은 문자열을 기본타입으로 변환하여 반환한다.
int x = Integer.parseInt("123");
float y = Float.parseFloat("23.5");
 
//숫자를 문자열로 변환
int i = 5;
String str = " " + i;
String str2 = String.valueOf(10);
 
int i = 15;
double d = 15.6;
String str3 = Integer.toString(i);
String str4 = Double.toString(d);
cs


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
package chapter14.javaBasicClass;
 
public class StringConvert {
 
    public static void main(String[] args) {
        // String 생성 실습
        String str1 = "hello";
        String str2 = new String("java");
        char[] arr = { 'g''o''o''d' };
        String str3 = new String(arr);
        String str4 = new String();
        str4 = str1 + " " + str2 + " " + str3;    //" " 는 공백문자열(띄어쓰기를 위해 작성)
        System.out.println(str4);
 
        // String을 숫자로 변환
        String s_i = "123";
        String s_f = "23.5";
        String s_d = "234.567";
        int i = Integer.valueOf(s_i).intValue();    //valueOf()는 그 래퍼 클래스 객체(Integer이면 Integer객체)를 반환하기 때문에
        float f = Float.valueOf(s_f).floatValue();    //기본타입으로 변환하는 intValue(), floatValue(), doubleValue()로 한번더 처리해야 한다.
        double d = Double.valueOf(s_d).doubleValue();
        System.out.println("String의 합 : " + s_i + s_f + s_d);    //문자열을 '+' 연산자로 연결하기만 함.
        System.out.println("숫자의 합 : " + (i + f + d));    //valueOf를 통해 기본타입으로 변환후 숫자들을 더함.
 
        int x = Integer.parseInt("123");
        float y = Float.parseFloat("23.5");
        System.out.println("x + y = " + (x + y));
 
        // 숫자를 String으로 변환
        System.out.println("x + y = " + x + y);    //괄호를 생략했을때 단순히 연결만 되는 이유는 "x + y = "도 문자열이기 때문에 그대로 연결만 된다.
        String str5 = String.valueOf(x);    //valueOf를 통해 숫자를 문자열로 변환
        System.out.println(str5 + 8);
        System.out.println(8 + str5);    //"문자열 + 숫자", "숫자 + 문자열" = 문자열
 
        String str6 = Integer.toString(i);    //래퍼 클래스의 toString()을 통해 래퍼 클래스의 기본 타입 값을 문자열로 변환
        String str7 = Float.toString(f);
        String str8 = Double.toString(d);
        System.out.println("str6 = " + str6);
        System.out.println("str7 = " + str7);
        System.out.println("str8 = " + str8);
    }
 
}
 
cs








문자열 조작과 비교

메서드 

설명 

int length() 

문자열의 길이 반환 

String concat(String str) 

현재 String객체와 파라미터 str을 하나의 문자열로 연결하여 반환 

String substring(int beginIndex, int endIndex) 

문자열을 beginIndex 위치부터 endIndex까지 잘라내어 반환 

String[] split(String regex) 

문자열을 구분자(파라미터)로 잘라 배열로 반환 

String trim() 

문자열의 앞, 뒤 공백 제거 

String toLowerCase() 

문자열을 모두 소문자로 변환 

String toUpperCase() 

문자열을 모두 대문자로 변환 

int indexOf(String str) 

문자열 내에서 파라미터 문자열이 처음 나타나는 위치 반환 

int lastIndexOf(String str) 

문자열 내에서 파라미터 문자열이 마지막 나타나는 위치 반환 

boolean contains(CharSequence s) 

문자열 내에 파라미터로 지정한 하위 문자열이 있는지를 검사하여 true, false를 반환 

String replace(charSequence target, 

                   CharSequence replacement) 

문자열 내에서 첫 번째 파라미터인 하위 문자열을 두 번째 파라미터 문자열로 변환 



메서드 

설명 

boolean endsWith(String suffix) 

문자열이 파라미터 문자열(suffix)로 끝나는지 검사

boolean startsWith(String prefix) 

문자열이 파라미터 문자열(prefix)로 끝나는지 검사 

int compareTo(String anotherString) 

두 문자열이 같은지를 비교하여 같으면 0을 반환 

boolean equals(Object anObject) 

두 객체가 같은지를 비교하는 메서드로 String클래스에서는 문자열이 같은지를 비교하여 true, false를 반환 


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
package chapter14.javaBasicClass;
 
public class StringTest {
 
    public static void main(String[] args) {
        System.out.println("concat() test : " + "abc".concat("def"));
        
        System.out.println("substring() test : " + "substring".substring(39));
        
        String color = "red, blue, white";
        String arr[] = color.split(",");
        System.out.println("split() test : ");
        for(int i=0; i<arr.length; i++) {
            System.out.println("arr[" + i + "] = " + arr[i]);
        }
        
        System.out.println("    trim() test : ".trim());
        
        System.out.println("toLowerCase() test : ".toLowerCase());
        System.out.println("toUpperCase() test : ".toUpperCase());
        
        System.out.println("indexOf() test : " + "abcdefghijk".indexOf("def"));
        
        System.out.println("lastIndexOf() test : " + "abcdefghijk".lastIndexOf("a"));
        System.out.println("lastIndexOf() test : " + "abcdefghijka".lastIndexOf("a"));
        
        System.out.println("contains() test : " + "on Air".contains("on"));
        System.out.println("replace() test : hello java".replace("java""world"));
        
        System.out.println("endWith() test : " + "abcdefg".endsWith("fg"));
        System.out.println("startWith() test : " + "abcdefg".startsWith("abc"));
        
        System.out.println("compareTo() test : " + "abcdefg".compareTo("abcdefg"));    //같으면 0을 반환
        System.out.println("equals() test : " + "abc".equals("abc"));        
    }
}
 
cs


























StringBuilder

: StringBuilder는 String클래스처럼 문자열을 처리하는 클래스지만 문자열을 수정하는 방법에 약간의 차이가 있다. 예를들어 "abc" + "def"를 처리할 때 String클래스는 메모리를 새로 할당 받아 "abcdef" 문자열을 새로 생성하지만, StringBuilder는 내부에 가변 길이의 배열을 가지고 있어서 "abc"문자열을 "abcdef"로 변경할 수 있다.


메서드

설명 

StringBuilder() 

기본 생성자로 capacity(내부 배열크기)는 16 

StringBuilder(int initCapacity) 

capacity를 파라미터 크기로 지정하는 생성자 

StringBuilder(String s) 

파라미터 문자열로 초기화 하는 생성자 

StringBuilder append(String s) 

파라미터 문자열을 원래의 문자열에 연결 

StringBuilder delete(int start, int end) 

문자열의 start위치에서 end-1까지 삭제 

StringBuilder insert(int offset, String s) 

두 번째 파라미터 문자열을 첫 번째 파라미터 위치에 삽입 

StringBuilder replace(int start, int end, String s) 

문자열의 start위치에서 end까지의 하위 문자열을 세 번째 파라미터 문자열로 교체 


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
package chapter14.javaBasicClass;
 
import java.util.Scanner;
 
public class StringBuilderTest {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        int i;
        for(i=0; i<3; i++) {
            System.out.println("단어를 입력하라");
            sb.append(sc.next());
        }
        
        System.out.println(sb);
        
        sb.delete(35);        //3번지에서 (5-1)번지 사이의 문자열 삭제
        System.out.println(sb);
        
        sb.insert(3"xxx");
        System.out.println(sb);    //3번지부터 xxx삽입
        
        sb.replace(35"yyy");
        System.out.println(sb);    //3번지부터 5번지까지의 xxx를 yyy로 replace
        
        sc.close();
    }
 
}
 
cs
















댓글

Designed by JB FACTORY