简体   繁体   English

按字母顺序比较字符串

[英]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").我想按字母顺序比较上面两个字符串(在这种情况下,“Project”然后“Sunject”,因为“P”在“S”之前)。 Does anyone know how to do that in Java?有谁知道如何在 Java 中做到这一点?

String.compareTo might or might not be what you need. String.compareTo可能是也可能不是您需要的。

Take a look at this link if you need localized ordering of strings.如果您需要对字符串进行本地化排序,请查看链接。

Take a look at the String.compareTo method.看一下String.compareTo方法。

s1.compareTo(s2)

From the javadocs:从javadocs:

The result is a negative integer if this String object lexicographically precedes the argument string.如果此字符串 object 按字典顺序在参数字符串之前,则结果为负 integer。 The result is a positive integer if this String object lexicographically follows the argument string.如果此字符串 object 按字典顺序跟随参数字符串,则结果为正 integer。 The result is zero if the strings are equal;如果字符串相等,则结果为零; compareTo returns 0 exactly when the equals(Object) method would return true.当 equals(Object) 方法返回 true 时,compareTo 返回 0。

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
} 

You can call either string's compareTo method (java.lang.String.compareTo).您可以调用任一字符串的 compareTo 方法 (java.lang.String.compareTo)。 This feature is well documented on the java documentation site .此功能在 java 文档站点上有详细记录

Here is a short program that demonstrates it:这是一个演示它的简短程序:

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();
    }
}

Here is a live demonstration that shows it works: http://ideone.com/Drikp3这是一个现场演示,表明它有效: http://ideone.com/Drikp3

For alphabetical order following nationalization, use Collator .对于国有化后的字母顺序,请使用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");
}

For a list of supported locales, see JDK 8 and JRE 8 Supported Locales .有关支持的语言环境列表,请参阅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]);
        }
   }
}

As others have mentioned, you can use String.compareTo , but that will sort all upper-case letters before all lower-case letters, so "Z" will come before "a".正如其他人所提到的,您可以使用String.compareTo ,但这会将所有大写字母排在所有小写字母之前,因此“Z”将排在“a”之前。

If you just want to sort them in alphabetical order regardless of case (so that "a" comes before "Z"), you can use String.compareToIgnoreCase :如果您只想按字母顺序对它们进行排序而不考虑大小写(因此“a”在“Z”之前),您可以使用String.compareToIgnoreCase

s1.compareToIgnoreCase(s2);

This returns a negative integer if s1 comes before s2 , a positive integer if s2 comes before s1 , and zero if they're equal.如果s1s2之前,则返回负 integer ,如果s2s1之前,则返回正 integer ,如果它们相等,则返回零。 Since this method ignores case completely, two strings that differ only by case are considered equal, for example "ABC".compareToIgnoreCase("abc") will return zero.由于此方法完全忽略大小写,因此仅区分大小写的两个字符串被视为相等,例如"ABC".compareToIgnoreCase("abc")将返回零。

As others suggested, you can use String.compareTo(String) .正如其他人建议的那样,您可以使用String.compareTo(String)

But if you are sorting a list of Strings and you need a Comparator , you don't have to implement it, you can use Comparator.naturalOrder() or Comparator.reverseOrder() .但是,如果要对字符串列表进行排序并且需要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);

Person.java人.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 +
            '}';
}

} }

PersonNameComparator人名比较器

import java.util.Comparator;

public class PersonNameComparator implements Comparator<Person> {


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

} }

PersonTest.java# PersonTest.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);});

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM