codeigniter 如何在一个列表中获取一个字符串的索引

2nc8po8w  于 4个月前  发布在  其他
关注(0)|答案(2)|浏览(33)
public int userCompare(String s1, int i1, String s2, int i2){
        String[] alphabety = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        String[] firstThing = s1.split("(?!^)");
        String[] secondThing = s2.split("(?!^)");
}

字符串
如何完成以下操作:
创建一个名为userCompare的方法,该方法将根据以下内容返回-1,1或0:我们有两个用户的数据,A和B,每个用户都有一个String名称和一个int id。目标是对用户进行排序。如果A在B之前,则返回-1,如果A在B之后,则返回1,如果它们相同,则返回0。首先按字符串名称排序,如果名字相同,则按身份证号码查找。

p8ekf7hl

p8ekf7hl1#

我会单独比较每个分量,然后使用signum严格得到1-10

public int userCompare(User a, User b) {
    int retVal = a.getName().compareTo(b.getName);
    if (retVal != 0) {
        return (int) Math.signum(retVal);
    }

    retVal = Integer.compare(a.getId(), b.getId());
    return (int) Math.signum(retVal);
}

字符串
旁注-对于Java中的排序,你不需要严格返回1-10,你可以只返回一个任意的正,负或零值。换句话说,signum的使用是有问题的,但不是严格要求排序。

o2g1uqev

o2g1uqev2#

我会在这里使用 String#compareTo 和 * String #compare* 方法。

int userCompare(String nameA, int idA, String nameB, int idB) {
    int t;
    if ((t = nameA.compareTo(nameB)) == 0)
        return Integer.compare(idA, idB);
    return t;
}

字符串
如果您希望实现实际的比较例程,请查看这些方法的 * 源代码 *。
对于 String,它只是 bytes 的遍历。
这里使用 StringLatin1#compareTo 方法。

  • GitHub StringLatin1.java
public static int compareTo(byte[] value, byte[] other, int len1, int len2) {
    int lim = Math.min(len1, len2);
    for (int k = 0; k < lim; k++) {
        if (value[k] != other[k]) {
            return getChar(value, k) - getChar(other, k);
        }
    }
    return len1 - len2;
}


而且,对于一个 *,它只是一个 * 关系 * 和 * 相等 * 的操作。

  • GitHub Integer.java
/**
 * Compares two {@code int} values numerically.
 * The value returned is identical to what would be returned by:
 * <pre>
 *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
 * </pre>
 *
 * @param  x the first {@code int} to compare
 * @param  y the second {@code int} to compare
 * @return the value {@code 0} if {@code x == y};
 *         a value less than {@code 0} if {@code x < y}; and
 *         a value greater than {@code 0} if {@code x > y}
 * @since 1.7
 */
public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

相关问题