Java Compare Strings

2019-06-04 22:57发布

 /**
 * A method to compare Strings
 * @param arg1
 * @param arg2
 * @return 
 */
public boolean myQuickCompare(String arg1, String arg2) {
    boolean a = arg1.length() == arg2.length();
    if (a) {
        for (int b = 0; b > arg1.length(); b++) {
            if (arg1.charAt(b) != arg2.charAt(b)) {
                a = false;
            }
        }
    }
    return a;
}

I understand that the for loop is the wrong way around, b will never be greater than the length of the string. How would you correct this problem?

What sensible variable names would you give for a and b?

5条回答
倾城 Initia
2楼-- · 2019-06-04 23:30

I always use StringUtils.compare ( Apache Commons ). This handles the null case for either String argument as well.

查看更多
三岁会撩人
3楼-- · 2019-06-04 23:30

A couple of things:

  1. When you compare strings for equality, use the .equals method. == is used to compare object references and see if they refer to the same instance. .equals actually compares the characters inside the String object.
  2. Even if you do things your way (which is incorrect), the for loop should look like this

    for (int b = 0; b < arg1.length(); b++)

查看更多
Rolldiameter
4楼-- · 2019-06-04 23:38

a => result b => current

It would be helpful to check if either of arguments is null.

查看更多
beautiful°
5楼-- · 2019-06-04 23:47

I understand that the for loop is the wrong way around, b will never be greater than the >length of the string. How would you correct this problem?

use equals() of String directly

What sensible variable names would you give for a and b?

a may be result

b may be index


Here is the implementation of equals() from open jdk 7

 public boolean equals(Object anObject) {
 1014           if (this == anObject) {
 1015               return true;
 1016           }
 1017           if (anObject instanceof String) {
 1018               String anotherString = (String)anObject;
 1019               int n = count;
 1020               if (n == anotherString.count) {
 1021                   char v1[] = value;
 1022                   char v2[] = anotherString.value;
 1023                   int i = offset;
 1024                   int j = anotherString.offset;
 1025                   while (n-- != 0) {
 1026                       if (v1[i++] != v2[j++])
 1027                           return false;
 1028                   }
 1029                   return true;
 1030               }
 1031           }
 1032           return false;
 1033       }
查看更多
男人必须洒脱
6楼-- · 2019-06-04 23:50

Use arg1.equals(arg2). No need for custom functions. Don't try to outsmart the developers of Java. Most of the time, they win.

查看更多
登录 后发表回答