Java | String Method

나경호·2022년 4월 9일
0

CS | Java

목록 보기
1/9
post-thumbnail

Java 문자열 메소드 정리

출처 | programiz

split()

Splits the string at the specified string (regex)
지정된 문자열(regex)에서 문자열을 분할합니다.

class Main {
  public static void main(String[] args) {
    String text = "Java is a fun programming language";

    // split string from space
    String[] result = text.split(" ");


    System.out.print("result = ");
    for (String str : result) {
      System.out.print(str + ", ");
    }
  }
}

// Output: result = Java, is, a, fun, programming, language,

compareTo()

Compares two strings in the dictionary order
사전 순서로 두 문자열을 비교합니다.

class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    String str2 = "Learn Kolin";
    int result;

    // comparing str1 with str2
    result = str1.compareTo(str2);

    System.out.println(result);
  }
}

// Output: -1

compareToIgnoreCase()

Compares two strings ignoring case differences
대소문자 차이를 무시하고 두 문자열을 비교합니다.

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "learn java";
        String str3 = "Learn Kolin";
        int result;

        // comparing str1 with str2
        result = str1.compareToIgnoreCase(str2);
        System.out.println(result); // 0

        // comparing str1 with str3
        result = str1.compareToIgnoreCase(str3);
        System.out.println(result); // -1

        // comparing str3 with str1
        result = str3.compareToIgnoreCase(str1);
        System.out.println(result); // 1
    }
}

length()

Returns the length of the string
문자열의 길이를 반환

class Main {
  public static void main(String[] args) {
      String str1 = "Java is fun";

      System.out.println(str1.length());

  }
}

// Output: 11

replace()

Replace all matching characters/text in the string
문자열에서 일치하는 모든 문자/텍스트 바꾸기

class Main {
  public static void main(String[] args) {
    String str1 = "bat ball";

    // replace b with c
    System.out.println(str1.replace('b', 'c'));

  }
}

// Output: cat call

replaceAll()

Replace all substrings matching the regex pattern
정규식 패턴과 일치하는 모든 하위 문자열 바꾸기

class Main {
  public static void main(String[] args) {
    String str1 = "Java123is456fun";

    // regex for sequence of digits
    String regex = "\\d+";

    // replace all occurrences of numeric
    // digits by a space
    System.out.println(str1.replaceAll(regex, " "));


  }
}

// Output: Java is fun

substring()

Returns a substring from the given string
주어진 문자열에서 부분 문자열을 반환합니다.

class Main {
  public static void main(String[] args) {
    String str1 = "java is fun";

    // extract substring from index 0 to 3
    System.out.println(str1.substring(0, 4));

  }
}

// Output: java

equals()

Compares two strings
두 문자열을 비교합니다.

class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    String str2 = "Learn Java";

    // comparing str1 with str2
    boolean result = str1.equals(str2);

    System.out.println(result);
  }
}

// Output: true

equalsIgnoreCase()

Compares two strings ignoring case differences
대소문자 차이를 무시하고 두 문자열을 비교합니다.

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "learn java";
        String str3 = "Learn Kolin";
        Boolean result;

        // comparing str1 with str2
        result = str1.equalsIgnoreCase(str2);
        System.out.println(result); // true

        // comparing str1 with str3
        result = str1.equalsIgnoreCase(str3);
        System.out.println(result); // false

        // comparing str3 with str1
        result = str3.equalsIgnoreCase(str1);
        System.out.println(result); // false
    }
}

contains()

Checks whether the string contains a substring
문자열에 하위 문자열이 포함되어 있는지 확인

class Main {
  public static void main(String[] args) {
    String str1 = "Java String contains()";

    // check if str1 contains "Java"
    boolean result = str1.contains("Java");

    System.out.println(result);
  }
}

// Output: true

indexOf()

Returns the index of the character/susbtring
문자/하위 문자열의 인덱스를 반환합니다.

class Main {
  public static void main(String[] args) {
    String str1 = "Java is fun";
    int result;

    // getting index of character 's'
    result = str1.indexOf('s');

    System.out.println(result);
  }
}

// Output: 6

trim()

Removes any leading and trailing whitespace
선행 및 후행 공백을 제거합니다.

class Main {
  public static void main(String[] args) {
    String str1 = "   Learn Java Programming      ";

    System.out.println(str1.trim());

  }
}

// Output: Learn Java Programming

charAt()

Returns the character at the given index
주어진 인덱스에 있는 문자를 반환

class Main {
  public static void main(String[] args) {
    String str1 = "Java Programming";

    // returns character at index 2
    System.out.println(str1.charAt(2));


  }
}

// Output: v

toLowerCase()

Converts characters in the string to lower case
문자열의 문자를 소문자로 변환

class Main {
  public static void main(String[] args) {
    String str1 = "JAVA PROGRAMMING";

    // convert to lower case letters
    System.out.println(str1.toLowerCase());

  }
}

// Output: java programming

concat()

Concatenates two strings and returns it
두 문자열을 연결하여 반환

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    String str2 = "Programming";

    // concatenate str1 and str2
    System.out.println(str1.concat(str2));

  }
}

// Output: JavaProgramming

valueOf()

Returns the string representation of a value
값의 문자열 표현을 반환합니다.

class Main {
  public static void main(String[] args) {

    double interest = 923.234d;

    // convert double to string
    System.out.println(String.valueOf(interest));

  }
}

// Output: 923.234

matches()

checks whether the string matches the given regex
문자열이 주어진 정규식과 일치하는지 확인

class Main {
  public static void main(String[] args) {

    // a regex pattern for
    // four letter string that starts with 'J' and end with 'a'
    String regex = "^J..a$";

    System.out.println("Java".matches(regex));

  }
}

// Output: true

startsWith()

Checks if the string begins with the given string
문자열이 주어진 문자열로 시작하는지 확인

class Main {
  public static void main(String[] args) {

    String str = "JavaScript";

    // checks if "JavaScript" starts with "Java"
    System.out.println(str.startsWith("Java"));

  }
}

// Output: true

endsWith()

Checks if the string ends with the given string
문자열이 주어진 문자열로 끝나는지 확인

class Main {
  public static void main(String[] args) {

    String str = "Java Programming";

    System.out.println(str.endsWith("mming")); // true
    System.out.println(str.endsWith("g")); // true
    System.out.println(str.endsWith("a Programming")); // true

    System.out.println(str.endsWith("programming")); // false
    System.out.println(str.endsWith("Java")); // false
  }
}

isEmpty()

Checks whether a string is empty or not
문자열이 비어 있는지 여부를 확인합니다.

class Main {
  public static void main(String[] args) {

    String str1 = "Java Programming";
    String str2 = "";

    System.out.println(str1.isEmpty()); // false
    System.out.println(str2.isEmpty()); // true

  }
}

intern()

Returns a canonical representation of the string
문자열의 표준 표현을 반환합니다.

class Main {
  public static void main(String[] args) {
    String a = "apple";
    String b = new String("apple");
    String c = b.intern()

    System.out.println(a==b); // false
    System.out.prrintln(a==c); // true
  }
}

getBytes()

Encodes the string into a sequences of bytes
문자열을 바이트 시퀀스로 인코딩

import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    String str = "Java";
    byte[] byteArray;

    // convert the string to a byte array
    // using platform's default charset
    byteArray = str.getBytes();
    System.out.println(Arrays.toString(byteArray));
  }
}

contentEquals()

Checks whether the string is equal to charSequence
문자열을 바이트 시퀀스로 인코딩

class Main {
  public static void main(String[] args) {
    String str = "Java";

    String str1 = "Java";
    StringBuffer sb1 = new StringBuffer("Java");
    CharSequence cs1 = "Java";

    String str2 = "JavA";
    StringBuffer sb2 = new StringBuffer("JavA");
    CharSequence cs2 = "JavA";

    System.out.println(str.contentEquals(str1)); // true
    System.out.println(str.contentEquals(sb1)); // true
    System.out.println(str.contentEquals(cs1)); // true

    System.out.println(str.contentEquals(str2)); // false
    System.out.println(str.contentEquals(sb2)); // false
    System.out.println(str.contentEquals(cs2)); // false
  }
}

Java String equals() Vs contentEquals()

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    StringBuffer sb1 = new StringBuffer("Java");

    System.out.println(str1.equals(sb1)); // false
    System.out.println(str1.contentEquals(sb1)); // true
  }
}

hashCode()

Returns a hash code for the string
문자열에 대한 해시 코드를 반환합니다.

class Main {
  public static void main(String[] args) {
    String str1 = "Java";
    String str2 = "Java Programming";
    String str3 = "";

    System.out.println(str1.hashCode()); // 2301506
    System.out.println(str2.hashCode()); // 1377009627

    // hash code of empty string is 0
    System.out.println(str3.hashCode()); // 0

  }
}

join()

Joins the given strings using the delimiter
구분 기호를 사용하여 주어진 문자열을 결합합니다.

class Main {
  public static void main(String[] args) {
    String str1 = "I";
    String str2 = "love";
    String str3 = "Java";

    // join strings with space between them
    String joinedStr = String.join(" ", str1, str2, str3);

    System.out.println(joinedStr);
  }
}

// Output: I love Java

replaceFirst()

Replace the first matching substring
일치하는 첫 번째 부분 문자열 바꾸기

class Main {
  public static void main(String[] args) {
      String str1 = "aabbaaac";
      String str2 = "Learn223Java55@";

      // regex for sequence of digits
      String regex = "\\d+";

      // the first occurrence of "aa" is replaced with "zz"
      System.out.println(str1.replaceFirst("aa", "zz")); // zzbbaaac

      // replace the first sequence of digits with a whitespace
      System.out.println(str2.replaceFirst(regex, " ")); // Learn Java55@
  }
}

subSequence()

Returns a subsequence from the string
문자열에서 하위 시퀀스를 반환합니다.

class Main {
  public static void main(String[] args) {
    String str = "Java Programming";

    System.out.println(str.subSequence(3, 8)); // a Pro
  }
}

toCharArray()

Converts the string to a char array
문자열을 char 배열로 변환

class Main {
  public static void main(String[] args) {
    String str = "Java Programming";

    // creating a char array
    char[] result;

    result = str.toCharArray();
    System.out.println(result); // Java Programming
  }
}

format()

Returns a formatted string
형식이 지정된 문자열을 반환합니다.

class Main {
  public static void main(String[] args) {

    String str = "Java";

    // format string 
    String formatStr = String.format("Language: %s", str);

    System.out.println(formatStr);
  }
}

// Output: Language: Java
profile
기억창고👩‍🌾

0개의 댓글