Java 像 strcmp 一样获取字符串之间的整数差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23934428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:12:30  来源:igfitidea点击:

Get integer difference between string just like strcmp

javastring-comparison

提问by Tomá? Zato - Reinstate Monica

I just need a function that will, for two given strings, return negative, positive or zero value. In C, strcmpis used:

我只需要一个函数,它可以为两个给定的字符串返回负值、正值或零值。在 C 中,strcmp使用:

char* a = "Hello";
char* b = "Aargh";

strcmp(a, b);  //-1
strcmp(a, a);  //0
strcmp(b, a);  //1

Does Java have any easy intuitive way to do it, or do I have to use the Comparatorinterface?

Java 是否有任何简单直观的方法来做到这一点,还是我必须使用Comparator界面?

采纳答案by dasblinkenlight

Does Java have any easy intuitive way to do it?

Java 是否有任何简单直观的方法来做到这一点?

Yes, it does: java.lang.Stringimplements Comparable<String>interface, with compareTofunction:

是的,它确实:java.lang.String实现Comparable<String>接口,具有compareTo功能:

int comparisonResult = a.compareTo(b);

There is also a case-insensitive version:

还有一个不区分大小写的版本:

int comparisonResult = a.compareToIgnoreCase(b);

回答by Reimeus

What about compareTo?

怎么样compareTo

int value = a.compareTo(b);

回答by slaadvak

The String.compareTomethod is the way to go in Java.

String.compareTo方法是Java的路要走。

How to use it :

如何使用它 :

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {

    String str1 = "tutorials", str2 = "point";

    // comparing str1 and str2
    int retval = str1.compareTo(str2);

    // prints the return value of the comparison
    if (retval < 0) {
       System.out.println("str1 is less than str2");
    }

    else if (retval == 0) {
       System.out.println("str1 is equal to str2");
    }

    else {
       System.out.println("str1 is greater than str2");
    }
  }
}

Output :

输出 :

str1 is less than str2

Example taken from : http://www.tutorialspoint.com/java/lang/string_compareto.htm

示例取自:http: //www.tutorialspoint.com/java/lang/string_compareto.htm

回答by codebox

You can use compareTobut should include a null check as well if you want to be safe:

您可以使用compareTo但如果您想安全,也应该包括一个空检查:

if (a != null){
    result = a.compareTo(b);
} else {
    //decide what to do here
}

回答by Levent Divilioglu

As it is previously answered, Java has a built-in String.compareTo(String anotherString)method, you should checkout the runtimesources (you should search google for rt.jar).

正如之前回答的那样,Java 有一个内置String.compareTo(String anotherString)方法,您应该检查运行时源(您应该在谷歌搜索rt.jar)。

However, here is a working sample with same logic applied on the compareTomethod;

但是,这里有一个工作示例,在该compareTo方法上应用了相同的逻辑;

Method Implementation

方法实现

public static int stringCompare(String str1, String str2) {
    char[] charArray1 = str1.toCharArray();
    char[] charArray2 = str2.toCharArray();

    int lim = Math.min(charArray1.length, charArray2.length);

    int k = 0;
    while (k < lim) {
        if (charArray1[k] != charArray2[k]) {
            return charArray1[k] - charArray2[k];
        }
        k++;
    }
    return charArray1.length - charArray2.length;
}

Demo Code

演示代码

public class StringCmp1 {

    public static void main(String[] args) {
        String str1 = "aa";
        String str2 = "ad";

        System.out.println("Comparison of '" + str1 + "' and '" + str2 + "'");
        System.out.println("Custom Method    : " + str1.compareTo(str2));
        System.out.println("Built-in Method  : " + stringCompare(str2, str1));

        System.out.println("\nComparison of '" + str2 + "' and '" + str1 + "'");
        System.out.println("Custom Method    : " + str2.compareTo(str1));
        System.out.println("Built-in Method  : " + stringCompare(str1, str2));
    }

    public static int stringCompare(String str1, String str2) {
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();

        int lim = Math.min(charArray1.length, charArray2.length);

        int k = 0;
        while (k < lim) {
            if (charArray1[k] != charArray2[k]) {
                return charArray1[k] - charArray2[k];
            }
            k++;
        }
        return charArray1.length - charArray2.length;
    }

}

Output

输出

Comparison of 'aa' and 'ad'
Custom Method    : -3
Built-in Method  : 3

Comparison of 'ad' and 'aa'
Custom Method    : 3
Built-in Method  : -3