[JAVA] Class String

kdkdhoho·2022년 1월 29일

이 글은 Java 8 API 공식문서에서 제게 필요한 부분만을 해석한 포스팅입니다.
오역과 의역에 주의하세요!

목차

  1. Class String
  2. Field
  3. Constructor
  4. Method
  5. 즐겨찾는 메소드

Class String

  • java.lang.String

  • String 인스턴스는 생성된 후 값이 변경되지 않는다. (immutable)

    String str = "abc";
    str += "d";

    의 경우 "abcd"라는 새로운 객체가 str에 저장되는 것이다.

  • String str = "abc";

    char[] data = {'a', 'b', 'c'};
    String str = new String(data);

    는 같다.

  • String class는 각 char sequence의 요소를 탐색하기, 문자열 비교, 문자열 찾기, 문자열 자르기, 대문자 혹은 소문자로 바꾸기를 위한 메소드를 포함한다.

  • Java는 특별히 String에 + 연산과 다른 객체를 string으로 바꾸기 위한 메소드를 제공한다.
    '+' 연산은 StringBuilder(or StringBuffer)append 메소드를 구현한 것이고,
    Java 모든 클래스에 상속되어 있는 toString()으로 다른 객체를 string으로 바꾼다.

  • 생성자에 별다른 지정이 없을 경우 인스턴스에 null이 전달된다.
    이 때문에, NullPointerException이 발생할 수 있다.

  • 문자열은 UTF-16 형식의 문자열을 나타낸다.

Field

  • static Comparator<String> CASE_INSENSITIVE_ORDER:
    정렬 시, 대소문자 구분없이 출력하기 위한 비교기
String str = {"a", "b", "c", "A", "B", "C"};
Arrays.sort(str, String.CASE_INSENSITIVE_ORDER);

# a A b B c C

Constructor

  • String()
    빈 char sequence가 나타나도록 초기화한다.

    String str = new String();
    System.out.print(str);
    
    # 
  • String(char[] value)
    인자로 받은 char 배열을 문자열로 할당한다.

    char[] chr = {'a', 'b', 'c'};
    String str = new String(chr);
    
    # abc
  • String(char[] value, int offset, int count)
    인자로 받은 value에서 offset 위치부터 count개 만큼 문자열로 초기화한다.

    char[] chr = {'a', 'b', 'c'};
    String str = new String(chr, 0, 2);
    
    # ab
  • String(String original)
    인자로 받은 String형의 변수를 그대로 가져다 문자열 객체로 초기화

    String abc = "abc";
    String def = new String(abc);
    
    # abc
  • String(StringBuffer buffer)
    인자로 받은 StringBuffer형의 변수를 문자열 객체로 초기화

    String abc = "abc";
    StringBuffer sb = new StringBuffer(abc);
    sb.append("d");
    
    String abcd = new String(sb);
    
    System.out.println(abcd);
    
    # abcd
  • String(StringBuilder builder)
    인자로 받은 StringBuilder형의 변수를 문자열 객체로 초기화

    String abc = "abc";
    StringBuilder sb = new StringBuilder(abc);
    sb.append("d");
    
    String abcd = new String(sb);
    
    System.out.println(abcd);
    
    # abcd

Method

  • char charAt(int index)
    지정한 index를 char형으로 반환

    String abc = "abc";
    char c = abc.charAt(2);
    
    # c
  • int codePoint(int index)
    지정한 index의 char를 Unicode를 반환한다.

    String abc = "abc";
    int a = abc.codePointAt(1);
    
    # 98 (a의 유니코드 숫자)
  • int compareTo(String anotherString)
    1) 비교대상(anotherString)이 기준값(str)에 포함되어 있는 경우 서로의 문자열 길이의 차이를 리턴한다.

    String abc = "abc";
    int result = abc.compareTo("abc"); # 0
    result = abc.compareTo(""); # 3 - 0 = 3

    2) 그렇지 않은 경우, 다른 시점에서 두 char의 unicode 값의 차를 반환한다.

    String abc = "abc";
    int result = abc.compareTo("d"); # 97(a) - 100(d) = -3
    result = abc.compareTo("ad"); # 98(b) - 100(d) = -2
  • int compareToIgnoreCase(String str)
    위와 동일하지만 대/소문자 구분을 하지 않는다.

    String abc = "abc";
    int result = abc.compareToIgnoreCase("aD");
    
    System.out.println(result); # -2
  • String concat(String str)
    인자로 받은 str을 기준 str 맨 뒤에 추가한 것을 반환한다.

    String abcd = "abc";
    abcd = abcd.concat("d"); # abcd
  • boolean contains(CharSequence s)
    문자열에 s가 포함되어 있다면 true, 아니라면 false 반환

    String abc = "abc";
    
    if(abc.contains("A"))
          System.out.println("not A");
    if(abc.contains("a"))
          System.out.println("Im a"); # Im a
  • boolean endsWith(String suffix)
    인자로 받은 String이 기준 문자열의 끝인지 판단한다.

    String str = "Hello World!";
    
    if(str.endsWith("World"))
    	System.out.println("World");
    if(str.endsWith("World!"))
    	System.out.println("World!"); # World!

    boolean startsWith(String prefix)
    문자열이 prefix로 시작하는지 판단하여 boolean값으로 반환한다.

  • boolean equals(Object anObject)
    anObject와 같은지 boolean 값으로 반환한다.

    String str = "Hello World!";
    String target = "Hello World";
    
    if(str.equals(target))
    	System.out.println("same");
    else
    	System.out.println("different"); # different
  • boolean equalsIgnoreCase(String anotherString)
    위와 개념은 동일하지만 매개변수로 String을 받아야하고, 대/소문자를 무시하여 비교한다.

    String str = "Hello World!";
    String target = "hello world!";
    
    if(str.equals(target))
    	System.out.println("this?");
    else if(str.equalsIgnoreCase(target))
    	System.out.println("how about this?"); # how about this
  • int indexOf(int ch(, int fromIndex))
    char형의 유니코드를 통해 문자열 내에서 처음으로 나타난 index를 반환한다.
    두 번째 매개변수로 fromIndex를 넣어주면 해당 index부터 탐색을 시작한다.

    String str = "Hello World!";
    
    int result = str.indexOf('o');
    System.out.println(result); # 4
  • boolean isEmpty()
    문자열이 비어있는지 판단한다.

    String str = "Hello World!";
    String str2 = "";
    
    System.out.println(str.isEmpty());
    System.out.println(str2.isEmpty());
    
    # false
    # true
  • static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

    ArrayList<String> arr = new ArrayList<>();
    arr.add("a");
    arr.add("r");
    arr.add("r");
    
    String str2 = "";
    str2 = str2.join("", arr);
    
    System.out.println(str2);
    # arr
  • int lastIndexOf(int ch)
    indexOf()와 똑같지만 제일 끝에서부터 탐색을 시작한다.

  • int length()
    문자열의 길이를 반환한다.

  • String replace(char oldChar, char newChar)
    문자열 내의 oldChar를 newChar로 바꾼다.

    String adc = "abc";
    adc = adc.replace('b', 'd');
    
    # adc

    String replace(CharSequence target, CharSequence replacement)
    문자열 내의 target을 replacement로 바꾼다.

    String str = "abc";
    str = str.replace("abc", "def");
    
    System.out.println(str);
    
    # def
  • replaceAll(String regex, String replacement)
    정규식을 사용하여 regex 전부를 replacement로 바꾼다.

    String str = "aaaaaaaaaabbbbbbbbbbbbbcccccccc";
    str = str.replaceAll("[ab]", "c");
    
    System.out.println(str);
    
    # ccccccccccccccccccccccccccccccc
  • String[] split(String regex)
    정규식을 사용하여 문자열을 나누어 String배열에 담아 반환한다.

  • String substring(int beginIndex)
    문자열을 beginIndex부터 끝까지 잘라서 반환한다.

    String substring(int beginIndex, int endIndex)
    문자열을 beginIndex부터 endIndex - 1까지 잘라 반환한다.

  • char[] toCharArray()
    문자열을 char배열로 반환한다.

  • toLowerCase() / toUpperCase()
    문자열 전체를 소문자 / 대문자로 바꾸어 반환한다.

  • String trim()
    문자열의 맨 앞뒤 공백을 제거한다.

    String str = "  abc ";
    str = str.trim();
    
    System.out.println(str);
    
    # abc
  • static String valueOf(Object obj)
    어떤 객체 혹은, 기본 타입의 값을 String형으로 바꾸어 반환한다.

    int i = 111;
    String result = String.valueOf(i);
    
    System.out.println(result);
    
    # 111

즐겨찾는 메소드

charAt()
compareTo()
concat()
contains()
equals()
indexOf()
isEmpty()
join()
length()
replace()
replaceAll()
split()
toLowerCase() / toUpperCase()
toCharArray()
trim()
valueof()

profile
newBlog == https://kdkdhoho.github.io

0개의 댓글