Comparing strings by their alphabetical order

String s1 = "Project";
String s2 = "Sunject";

I want to compare the two above string by their alphabetic order (which in this case "Project" then "Sunject" as "P" comes before "S"). Does anyone know how to do that in Java?

460468 次浏览

看一下 String.compareTo方法。

s1.compareTo(s2)

来自 javadocs:

如果是负整数,则结果为负整数 这个字符串对象 在参数字符串之前 结果是一个正整数,如果 字符串对象 在参数字符串后面 如果字符串为 返回0 当 equals (Object)方法将 返回真值。

String a = "...";
String b = "...";


int compare = a.compareTo(b);


if (compare < 0) {
//a is smaller
}
else if (compare > 0) {
//a is larger
}
else {
//a is equal to b
}

String.compareTo可能是您需要的,也可能不是。

如果需要字符串的本地化排序,请查看 这个链接。

可以调用字符串的 compareTo 方法(java.lang. String.compareTo)。

下面是一个简短的演示程序:

class StringCompareExample {
public static void main(String args[]){
String s1 = "Project"; String s2 = "Sunject";
verboseCompare(s1, s2);
verboseCompare(s2, s1);
verboseCompare(s1, s1);
}


public static void verboseCompare(String s1, String s2){
System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");


int comparisonResult = s1.compareTo(s2);
System.out.println("The result of the comparison was " + comparisonResult);


System.out.print("This means that \"" + s1 + "\" ");
if(comparisonResult < 0){
System.out.println("lexicographically precedes \"" + s2 + "\".");
}else if(comparisonResult > 0){
System.out.println("lexicographically follows \"" + s2 + "\".");
}else{
System.out.println("equals \"" + s2 + "\".");
}
System.out.println();
}
}

下面是一个现场演示,显示了它的工作原理: http://ideone.com/Drikp3

对于国有化后的字母顺序,使用 Collator

//Get the Collator for US English and set its strength to PRIMARY
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
if( usCollator.compare("abc", "ABC") == 0 ) {
System.out.println("Strings are equivalent");
}

有关受支持的地区的列表,请参见 支持 JDK 8和 JRE 8的语言环境

import java.io.*;
import java.util.*;
public class CandidateCode {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int n =Integer.parseInt(sc.nextLine());
String arr[] = new String[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextLine();
}




for(int i = 0; i <arr.length; ++i) {
for (int j = i + 1; j <arr.length; ++j) {
if (arr[i].compareTo(arr[j]) > 0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i = 0; i <arr.length; i++) {
System.out.println(arr[i]);
}
}
}

正如其他人建议的那样,您可以使用 String.compareTo(String)

但是,如果您正在对字符串列表进行排序,并且需要一个 Comparator,那么您不必实现它,您可以使用 Comparator.naturalOrder()Comparator.reverseOrder()

String s1 = "Project";
String s2 = "Sunject";


//print smaller one using compareTo() function
if(s1.compareTo(s2)<0) System.out.println(s1);
//if s1 is smaller then function returns negative which is less than 0 so s1
//is smaller
else System.out.println(s2); // else s2 is smaller


//print larger one using compareTo() function
if(s1.compareTo(s2)>0) System.out.println(s1);
//is s1 is larger function will give positive so print s1 else s2
else System.out.println(s2);

正如其他人提到的,您可以使用 String.compareTo,但是它将在所有小写字母之前对所有大写字母进行排序,因此“ Z”将在“ a”之前。

如果你只是想把它们按字母顺序排序而不考虑大小写(这样“ a”在“ Z”之前) ,你可以使用 String.compareToIgnoreCase:

s1.compareToIgnoreCase(s2);

如果 s1s2之前,返回一个负整数; 如果 s2s1之前,返回一个正整数; 如果它们相等,返回零。因为这个方法完全忽略大小写,所以只有大小写不同的两个字符串被认为是相等的,例如 "ABC".compareToIgnoreCase("abc")将返回零。

Person.java

import java.util.Objects;
public class Person implements Comparable {
String firstName;
String lastName;
Integer age;
Integer DOBYear;


public Person(String firstName, String lastName, Integer age, Integer DOBYear) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.DOBYear = DOBYear;
}


public String getFirstName() {
return firstName;
}


public void setFirstName(String firstName) {
this.firstName = firstName;
}


public String getLastName() {
return lastName;
}


public void setLastName(String lastName) {
this.lastName = lastName;
}


public Integer getAge() {
return age;
}


public void setAge(Integer age) {
this.age = age;
}


public Integer getDOBYear() {
return DOBYear;
}


public void setDOBYear(Integer DOBYear) {
this.DOBYear = DOBYear;
}


@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(age, person.age) && Objects.equals(DOBYear, person.DOBYear);
}


@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age, DOBYear);
}


@Override
public int compareTo(Object o) {
Person p = (Person) o;
return p.getAge() > this.getAge() ? -1: p.getAge() == this.getAge() ? 0 : 1;
}


@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
", DOBYear=" + DOBYear +
'}';
}

}

人名比较器

import java.util.Comparator;


public class PersonNameComparator implements Comparator<Person> {




@Override
public int compare(Person o1, Person o2) {
return o1.getFirstName().compareTo(o2.getFirstName());
}

}

Java #

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;


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


System.out.println("Hello World");
Person p1 = new Person("Umesh","Bhutada",31,1991);
Person p2 = new Person("Deepali","Baheti",29,1992);
Person p3 = new Person("Romeet","Zanwar",5,2017);


ArrayList<Person> arr1 = new ArrayList<Person>( Arrays.asList(p1,p2,p3));
Collections.sort(arr1);


arr1.forEach(person -> {System.out.println( person);});


System.out.println("End of World");


System.out.println("test 2");


Collections.sort(arr1,new PersonNameComparator());
arr1.forEach(person -> {System.out.println( person);});


}

}