String class

coding by 스플릿·2022년 1월 4일

Java1

목록 보기
41/44

String class

문자열을 저장하고 이를 다루는데 필요한 메서드를 제공하는 클래스

public final class String implements java.io.Serializable, Comparable{
    private char [] value;
    ....
}
  • final클래스기에 조상클래스가 될 수 없으며 char [] 에 문자열이 저장된다.
    ( 생성후에는 읽어 올 수만 있고 변경할 수는 없다. )

  • + 연산자로 문자열이 결합하는 경우는 새로운 String 인스턴스에 결합 된 문자열이 저장되며 이때마다 새로운 String 인스턴스가 생기기에 결합이나 추출이 많은 경우는 StringBuffer 클래스를 사용한다.

    • String 생성
      • new 연산자로 String 인스턴스를 생성한 경우는 항상 새로운 인스턴스가 생성
      • 문자열 리터럴을 지정할 때는 이미 존재하는 것을 재사용한다.
public class Main{
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");
        String str4 = new String("Hello");
        is_same(str1, str2);
        is_same(str3, str4);
    }
    static void is_same(String a, String b){
        if(a==b)
            System.out.println("Same");
        else
            System.out.println("Not same");
    }
}
/* 출력 : 
Same
Not same
*/

String 리터럴

  • 자바 소스파일에 포함된 모든 문자열 리터럴은 컴파일 시에 클래스 파일에 저장된다.

  • 이때 같은 문자열 리터럴은 한번 저장된 String 인스턴스 주소를 참조하게 된다.

  • 빈 문자열도 존재할 수 있다. ( 길이가 0인 배열이 존재할 수 있다는 말과 같은 말이다. )

생성자와 메서드

생성자

생성자예제결과
String( String s )String s = new String("Hello")s = "Hello"
String( char [] value )char [] c = { 'H','e','l','l','o' };
String s = new String(c);
s = "Hello"
String( StringBuffer buf )StringBuffer sb = new StringBuffer("Hello");
String s = new String(sb)
s = "Hello"

메서드

메서드예제 ( String str = "Hello"; )결과
char charAt( int index )
index에 있는 문자를 반환한다.
char c = str.charAt(0)c ='H'
int compareTo( String str )
문자열끼리 사전순서로 비교해서 같으면 0 빠르면 -1 늦으면 1
int i = "aaa".compareTo("aaa");
int i2 = "aaa".compareTo("bbb");
int i3 = "bbb".compareTo("aaa");
i = 0
i2 = -1
i3 = 1
String concat( String str )
문자열 뒤에 덧붙인다.
String s2= str.concat(" World");s2 = "Hello World"
boolean contains(CharSequence s)
지정된 문자열이 포함되었는지 체크
boolean b = str.contains("el");b = true
boolean endsWith(String suffix)
지정된 문자열로 끝나는지 체크
boolean b = str.endsWith("lo");b = true
boolean equals( Object obj )
매개변수인 문자열(obj)와 String인스턴스의 value와 같으면 true
obj가 String클래스가 아니거나 문자열이 다르면 false
boolean b = str.equals("Hello");
boolean b2 = str.equals("hello");
b = true
b2 = false
boolean equalsIgnoreCase(String str)
매개변수인 String인스턴스의 value와 대소문자 없이 비교한다
boolean b = str.equalsIgnoreCase("hELLO");b = true
int indexOf(int ch)
주어진 문자(ch)가 존재하면 인덱스를 없으면 -1를 반환
int i = str.indexOf('H');i = 0
int lastIndexOf(int ch)
주어진 문자(ch)를 끝부터 탐색해서 존재하면 인덱스를 없으면 -1를 반환
int i = str.lastIndexOf('l');
int i2 = str.indexOf('l');
i = 4
i2 = 3
int indexOf(int ch, int pos)
주어진 문자(ch)가 위치(pos) 이후부터 확인하여 존재하면 인덱스를 없으면 -1를 반환
int i = str.indexOf('H',0 );
int i2 = str.indexOf('H', 1);
i = 0
i2 = -1
int indexOf(String str)
주어진 문자열이 존재하면 인덱스를 없으면 -1을 반환
int i = str.indexOf("He");i = 0
int lastIndexOf(String str)
주어진 문자열을 끝부터 탐색하여 존재하면 인덱스를 없으면 -1을 반환
String str = "HIoHI";
int i = str.indexOf("HI");
int i2 = str.lastIndexOf("HI");
i = 0
i2 = 3
String intern()
문자열을 String pool에 등록하며 pool에 있을 경우는 문자열의 주소값을 반환
https://simple-ing.tistory.com/3
String str2 = new String("Hello");
String str3 = "Hello";
System.out.print((str1 == str2)?true:false);
System.out.print((str1 == str3)?true:false);
System.out.print((str1 == str2.intern())?true:false);
출력 : falsetruetrue
int length()
문자열의 길이를 알려준다
int i = str.length();i = 5
String replace(char old, char new)
문자열에서 old를 new로 바꾼 문자열을 반환한다
String new = str.replace('H','C');new = "Cello"
String replace( CharSequence old, CharSequence new )
문자열에서 old와 같은 문자열을 new로 바꾼다
String new = str.replace("H","C");new = "Cello"
String replaceAll(CharSequence old, CharSequence new)
https://djusti.tistory.com/8
String str = "IIJJKKIIJJKK";
String str1 = str.replaceAll('II','ZZ');
str1 = "ZZJJKKZZJJKK"
String replaceFirst(CharSequence old, CharSequence new)
문자열에서 old와 같은 첫번째 문자열을 new로 바꾼다
String str = "IIJJKKIIJJKK";
String str1 = str.replaceFirst('II','ZZ');
str1 = "ZZJJKKIIJJKK"
String [] spilt ( Stringm regex )
문자열을 분리자로 나누어 문자열 배열에 담아 반환
String str = "hi,hello,bye";
String [] arr = str.split(",");
arr = { "hi", "hello", "bye" }
String [] spilt ( Stringm regex, int limit )
문자열을 분리자로 나누어 문자열 배열에 limit 수만큼만 담아 반환
String str = "hi,hello,bye";
String [] arr = str.split(",", 2);
arr = { "hi", "hello,bye" }
boolean startsWith( String prefix )
문자열이 prefix로 시작되는지 체크한다
boolean b = str.startsWith("H");b = true
String substring ( int begin, int end )
문자열에서 begin 인덱스부터 end 인덱스까지의 범위에 포함된 문자열을 얻는다
String str1 = str.substring(2);
String str2 = str.substring(1,4);
str = "llo"
str2 = "ell"
String toString()String 인스턴스에 저장된 문자열을 반환
String toLowerCase()모두 소문자로 변환하여 반환
String toUpperCase모두 대문자로 변환하여 반환
String trim()제일 앞과 제일 끝 공백을 모두 없애서 반환
String valueOf()매개변수를 문자열로 변환하여 반환한다.

0개의 댓글