startsWith(), endsWith() 함수

TaeYang Lim·2020년 1월 17일
1

프로그래머스의 전화번호 목록 문제를 풀기 위해 고민하던 중 처음으로 접해 본 함수가 존재해 포스팅 해보려고 한다.

프로그래머스의 해당 문제는 어떠한 문자열이 다른 문자열의 접두사인지 확인 하는 문제 였는데, 처음에는 contains을 이용해 풀어보려고 했으나, 이것은 접두사 즉 시작이 아닌 포함의 여부에 따라 리턴 시켜주었기에 정답은 아니였고 소개하고자 하는 함수를 찾아 사용해보게 되었다.

startsWith()


인수로 지정하는 문자열로 시작하는 경우 True를 리턴하고, 그렇지 않다면 False 값을 반환한다.
문자열의 시작 부분에 공백이 존재한다면 공백으로 시작 하는 것으로 인식 하기에 시작 부분에 공백은 없어야 한다.

public class StringMethods {
    public static void main(String[] args) {
        String str = "HELLO I'm GirrafeLim! ";
        System.out.println(str.startsWith("HEL")); // return True
        System.out.println(str.startsWith("hel")); // return False
    }
}

또한 startsWith() 함수는 toffset을 지정해 줄 수 있다.

public class StringMethods {
    public static void main(String[] args) {
        String str = "This is Girrafe";
        System.out.println(str.startsWith("is", 2)); // return True
        System.out.println(str.startsWith("is", 5)); // return True
        System.out.println(str.startsWith("is", 7)); // return False
    }
}

startsWith
public boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
Parameters:
prefix - the prefix.
toffset - where to begin looking in this string.
Returns:
true if the character sequence represented by the argument is a prefix of the substring of this object starting at index toffset; false otherwise. The result is false if toffset is negative or greater than the length of this String object; otherwise the result is the same as the result of the expression
this.substring(toffset).startsWith(prefix)

endsWith()


인수로 지정하는 문자열로 끝나는 경우 True를 리턴하고, 그렇지 않다면 False 값을 반환한다.
문자열의 끝부분에 공백이 존재한다면 공백으로 끝나는 것으로 인식 하기에 끝 부분에 공백은 없어야 한다.

public class StringMethods {
    public static void main(String[] args) {
        String str = "HELLO I'm GirrafeLim!";
        System.out.println(str.endsWith("GirrafeLim!")); // return True
        System.out.println(str.endsWith("girrafeLim!")); // return False
    }
}
profile
Java & Backend Developer

0개의 댓글