2013-12-07 2 views
5

두 문자열을 비교하여 알파벳순으로 정렬하고 싶습니다. 나는 현재 두 개의 배열을 문자열로 만들고 두 배열을 비교하는 것을 정렬하고있다.두 문자열 비교 및 ​​알파벳 순서로 정렬하기

String a="LetterA"; 
String b="ALetterB"; 
String[] array1={a.toLowerCase(),b.toLowerCase()}; 
String[] array2={a.toLowerCase(),b.toLowerCase()}; 
Arrays.sort(array2); 
if (Arrays.equals(array1, array2)){ 
    System.out.println(a+" is before "+b); 
} 
else{ 
    System.out.println(b+" is before "+a); 
} 

이것은 작동하지만 시간과 메모리를 소비합니다. 누구든지이 일을하는 더 좋은 방법을 제안 할 수 있다면 고맙겠습니다.

+1

목표는 무엇인가? 더 자세히 설명해 주시겠습니까? –

답변

15

힌트 : 모든 기본 데이터 형식 클래스는 java 구현 Comparable interface입니다. 그냥 간단하고 우아한 코드를보고 당신이 preoptimize하지 않으려면

String a="LetterA"; 
String b="ALetterB"; 
int compare = a.compareTo(b); 
if (compare < 0){ 
    System.out.println(a+" is before "+b); 
} 
else if (compare > 0) { 
    System.out.println(b+" is before "+a); 
} 
else { 
    System.out.println(b+" is same as "+a); 
} 
+2

일반 ASCII 모드가 아닌 경우이 전략은 제대로 작동하지 않습니다. http://stackoverflow.com/a/12927962/2087666 –

+0

주의 : 대문자의 ASCII 값은 작은 문자보다 작습니다. 1> a = "Ax"및 b = "aa"또는 2> a = "aa"및 b = "AA"와 같은 경우 ... 결과는 예상되는 사전 순 정렬과 모순됩니다. 두 문자열을 공통 "사례"로 변환 한 다음 비교하는 것이 좋습니다. – Deepeshkumar

1
int compare = a.compareTo(b); 
if (compare < 0){ 
    System.out.println(a + " is before " +b); 
} else if (compare > 0) { 
    System.out.println(b + " is before " +a); 
} else { 
    System.out.println("Strings are equal") 
} 
+0

동등 함을 추가하십시오 :) –

+0

완료 - 캐시 된 비교. – irla

1

, 자바 (8)에서 다음과 같이 할 수 있습니다

String[] sorted = Stream.of(a, b).sorted().toArray(String[]::new); 
System.out.println(sorted[0] + " is before " + sorted[1]); 
관련 문제