java 用Java中的ascii值比较2个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26553889/
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-11-02 10:08:38  来源:igfitidea点击:

Comparing 2 strings by ascii values in Java

javareturncompare

提问by DynoDimo

I have to write a method to compare strings alphabetically and return an int. I can't use any built-in functions and I'm supposed to use a forloop.

我必须编写一个方法来按字母顺序比较字符串并返回一个int. 我不能使用任何内置函数,我应该使用for循环。

I'm unsure about how to deal with the strings being of different lengths. At the moment my main issue is that the code is only comparing the first char of each string then returning the int, but I can't put return comparison;outside of the for loop

我不确定如何处理不同长度的字符串。目前我的主要问题是代码只是比较每个字符串的第一个字符然后返回 int,但我不能放在return comparison;for 循环之外

public class poop {
    public static int Compare(String s1, String s2) {

       for (int i = 0; i < s1.length() && i < s2.length(); i++) {

           int comparison = 0;
           int ascii1 = 0;
           int ascii2 = 0;
           //convert chars into their ascii values
           ascii1 = (int) s1.charAt(i); 
           ascii2 = (int) s2.charAt(i); 

           //treat capital letters as lower case
           if (ascii1 <= 95) {
               ascii1 += 32;
           } if (ascii2 <= 95) {
               ascii1 += 32;
           }

           if (ascii1 > ascii2) {
               comparison = 1;
           } else if (ascii1 < ascii2) {
                 comparison = -1;
           } else { 
                 comparison = 0;
           }

       } 
       return comparison;
    }

    public static void main(String[] args) {
        String s1 = "aba";
        String s2 = "aaa";
        System.out.println(Compare(s1,s2));
  }
}

回答by Barranka

If you are comparing alphabetically, that means that the first different character in the string defines the difference. For example: aabgoes before aacbecause of the c.

如果按字母顺序进行比较,则意味着字符串中的第一个不同字符定义了差异。例如:aab之前去aac的,因为c

As for different length strings, larger strings go after smaller strings (a dictionary uses that convention). So aaaagoes afteraaa, because aaaais larger.

对于不同长度的字符串,较大的字符串在较小的字符串之后(字典使用该约定)。所以aaaa之后aaa,因为aaaa更大。

So, let's get it done:

所以,让我们完成它:

/**
 * Will return an integer bigger than 1 if s1 is "bigger" than s2
 */
public static int compareStrings(String s1, String s2) {
    int comparison = 0;
    int c1, c2;
    for(int i = 0; i < s1.length() && i < s2.length(); i++) {
        c1 = (int) s1.toLowerCase().charAt(i);   // See note 1
        c2 = (int) s2.toLowerCase().charAt(i);   // See note 1
        comparison = c1 - c2;   // See note 2

        if(comparison != 0)     // See note 3
            return comparison;
    }
    if(s1.length() > s2.length())    // See note 4
        return 1;
    else if (s1.length() < s2.length())
        return -1;
    else
        return 0;
}

Notes:

笔记:

  1. I use the toLowerCase()method to convert the strings to lower case. If you can't use any "built-in" methods, you can use your conversion (that ASCII += 32piece). However, you must be careful: You must check that the character value is an alphabetic character before converting them like this (Use google to find an ASCII table and check which are the valid alphabetic character values)
  2. c1and c2are integers, so comparison = c1 - c2will hold the difference between those integers (characters).
  3. If comparison == 0, that means that the characters are equal, so nothing is done. But if comparison != 0, the characters are different; if comparison > 0that means that c1is "bigger" than c2, so s1is larger (look the first paragraph of my answer); if comparison < 0then s2is bigger.

    So, if comparison != 0, then you can return its value. Remember: the returnsentence does two things: It returns a value andexits the function. So the execution of the forloop is stopped too.

  4. The previous code solves the issue for the minimum string length. But, as posted in your question, you must deal with the case where the strings have different lengths. That last part of the code deals with them (and it can only be reached if comparisonis still 0):
    • If s1.lenght() > s2.length(), then s1is "bigger" than s2, so a positive value (+1) is returned.
    • If s1.lenght() < s2.length(), then s1is "smaller" than s2, so a negative value (-1) is returned.
    • In any other case, it would mean two things:

      (a) that all the chars of both strings are equal (because comparison == 0), and

      (b) that the length of both strings are equal

      so the strings areequal, and a zero value must be returned.

  1. 我使用该toLowerCase()方法将字符串转换为小写。如果您不能使用任何“内置”方法,则可以使用您的转换(那ASCII += 32部分)。但是,您必须小心:在像这样转换它们之前,您必须检查字符值是否是字母字符(使用谷歌查找 ASCII 表并检查哪些是有效的字母字符值)
  2. c1c2是整数,因此comparison = c1 - c2将保留这些整数(字符)之间的差异。
  3. 如果comparison == 0,则表示字符相等,所以什么都不做。但是如果comparison != 0,则字符不同;如果comparison > 0这意味着c1比“更大” c2,那么s1更大(看我答案的第一段);如果comparison < 0然后s2更大。

    所以,如果comparison != 0,那么你可以返回它的值。记住:这return句话做了两件事:它返回一个值退出函数。所以for循环的执行也停止了。

  4. 前面的代码解决了最小字符串长度的问题。但是,正如您在问题中发布的那样,您必须处理字符串长度不同的情况。代码的最后一部分处理它们(并且只有在comparisonis still 时才能到达0):
    • 如果s1.lenght() > s2.length(),则s1“大于” s2,因此+1返回正值 ( )。
    • 如果s1.lenght() < s2.length(),则s1“小于” s2,因此-1返回负值 ( )。
    • 在任何其他情况下,这意味着两件事:

      (a) 两个字符串的所有字符都相等(因为comparison == 0),并且

      (b) 两个字符串的长度相等

      所以字符串相等的,并且必须返回一个零值。