java.lang.String.compareTo() 사용법
참고 문서 : https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#compareTo-java.lang.String-
String (Java SE 9 & JDK 9 )
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum
docs.oracle.com
문자열 비교 compareTo()
public int compareTo(String anotherString)
사용 예시: str_1.compareTo(str_2)
return값은 총 3가지, 0과 음의 정수, 양의 정수이다.
0: str_1과 str_2가 똑같다.
음의 정수: str_2보다 str_1이 사전적으로 앞선다.
양의 정수: str_2보다 str_1이 사전적으로 뒤에 있다.
다른 문자열은 총 3가지 경우가 있다.
(1) 어떤 index의 문자가 다르다.
(2) 두 문자열 a, b의 길이가 다르다.
(3) (1)+(2) 둘다 다르다.
(1) 어떤 index(k)에서의 문자가 다르다.
they have different characters at some index that is a valid index for both strings [oracle 원문 참고]
this.charAt(k)-anotherString.charAt(k)
(1 예시) str_1 = "ABCD", str_2 = "ABcD"
index 2에서 C, c가 다르다. 이 둘의 unicode value(ACII) 차이를 구한다.
str_1.compareTo(str_2) == 67-99 == -32
(2) 두 문자열의 길이가 다르다.
상대적으로 짧은 문자열이 다른 문자열을 앞선다. 두 문자열 길이의 차이를 리턴한다.
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings.[oracle 원문 참고]
this.length()-anotherString.length()
(2 예시) str_1 = "ABCD", str_2 = "AB"
str_1.compareTo(str_2) == 4 - 2 = 2
(3) (1) + (2)
(3 예시)
str_1 = "ABCD", str_2 = "ab"
str_1.compareTo(str_2) == 65 - 97 = -32
+ 대소문자 구분하지 않고 compareTo() => compareToIgnoreCase()
String (Java SE 9 & JDK 9 )
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum
docs.oracle.com
숫자 비교 compareTo()
return 양수 : 크다 / return 0 : 같다 / return 음수 : 작다
단순 int 비교 : Integer.compare(int x, int y)