String 源码解析

一、charAt

返回指定位置的字符

eg:     "abcde".charAt(1)  结果为b

/**
 * Returns the {@code char} at {@code index}.
 * @throws IndexOutOfBoundsException if {@code index < 0} or {@code index >= length()}.
 */
public native char charAt(int index);


二、compareTo

两个字符串进行比较(一次只比较一个字符),结果如下:

1)遇到两个字符不同时,则结束比较,返回第一个字符与第二个字符的差值

     eg:  “abc”.compareTo("abd")   ,由于c与d不同,结束比较,返回c-d的值-1(返回的是他们ASCII差值)

2)如果两个字符串比较都相同,则比较两个字符串的长度

     eg:  “abc”.compareTo("abcd"),返回-1

                    “abc”.compareTo("abc"),返回0

/**
 * Compares this string to the given string.
 *
 * <p>The strings are compared one {@code char} at a time.
 * In the discussion of the return value below, note that {@code char} does not
 * mean code point, though this should only be visible for surrogate pairs.
 *
 * <p>If there is an index at which the two strings differ, the result is
 * the difference between the two {@code char}s at the lowest such index.
 * If not, but the lengths of the strings differ, the result is the difference
 * between the two strings' lengths.
 * If the strings are the same length and every {@code char} is the same, the result is 0.
 *
 * @throws NullPointerException
 *             if {@code string} is {@code null}.
 */
public native int compareTo(String string);

三、compareToIgnoreCase

两个字符串进行比较,忽略大小写,其他参照compareTo

/**
 * Compares this string to the given string, ignoring case differences.
 *
 * <p>The strings are compared one {@code char} at a time. This is not suitable
 * for case-insensitive string comparison for all locales.
 * Use a {@link java.text.Collator} instead.
 *
 * <p>If there is an index at which the two strings differ, the result is
 * the difference between the two {@code char}s at the lowest such index.
 * If not, but the lengths of the strings differ, the result is the difference
 * between the two strings' lengths.
 * If the strings are the same length and every {@code char} is the same, the result is 0.
 *
 * @throws NullPointerException
 *             if {@code string} is {@code null}.
 */
public int compareToIgnoreCase(String string) {
    int result;
    int end = count < string.count ? count : string.count;
    char c1, c2;
    for (int i = 0; i < end; ++i) {
        if ((c1 = charAt(i)) == (c2 = string.charAt(i))) {
            continue;
        }
        c1 = foldCase(c1);
        c2 = foldCase(c2);
        if ((result = c1 - c2) != 0) {
            return result;
        }
    }
    return count - string.count;
}
/**
 * This isn't equivalent to either of ICU's u_foldCase case folds, and thus any of the Unicode
 * case folds, but it's what the RI uses.
 */
private char foldCase(char ch) {
    if (ch < 128) {
        if ('A' <= ch && ch <= 'Z') {
            return (char) (ch + ('a' - 'A'));
        }
        return ch;
    }
    return Character.toLowerCase(Character.toUpperCase(ch));
}

四、concat

字符串拼接

(concat与+的效率问题可参考:http://blog.csdn.net/qq_34206198/article/details/51862477

/**
 * Concatenates this string and the specified string.
 *
 * @param string
 *            the string to concatenate
 * @return a new string which is the concatenation of this string and the
 *         specified string.
 */
public native String concat(String string);


五、copyValueOf

将指定字符数组转换成字符串

/**
 * Creates a new string by copying the given {@code char[]}.
 * Modifying the array after creating the string has no
 * effect on the string.
 *
 * @throws NullPointerException
 *             if {@code data} is {@code null}.
 */
public static String copyValueOf(char[] data) {
    return StringFactory.newStringFromChars(data, 0, data.length);
}
eg:

public static void main(String[] args) {
    char[] data={'1','2','3'};
    System.out.print(String.copyValueOf(data));
}
结果:




六、copyValueOf(char[] data, int start, int length)

将指定字符数组转换成字符串

start:指定data的起始位置

length:指定需要转换的个数

/**
 * Creates a new string by copying the given subsequence of the given {@code char[]}.
 * Modifying the array after creating the string has no
 * effect on the string.

 * @throws NullPointerException
 *             if {@code data} is {@code null}.
 * @throws IndexOutOfBoundsException
 *             if {@code length < 0, start < 0} or {@code start + length >
 *             data.length}.
 */
public static String copyValueOf(char[] data, int start, int length) {
    return StringFactory.newStringFromChars(data, start, length);
}
eg:

public static void main(String[] args) {
    char[] data={'1','2','3'};
    System.out.print(String.copyValueOf(data,0,2));
}
结果:




七、endWith

判断是否以某字符串结尾

/**
 * Compares the specified string to this string to determine if the
 * specified string is a suffix.
 *
 * @throws NullPointerException
 *             if {@code suffix} is {@code null}.
 */
public boolean endsWith(String suffix) {
    return regionMatches(count - suffix.count, suffix, 0, suffix.count);
}

/**
 * Returns true if the given subsequence of the given string matches this string starting
 * at the given offset.
 *
 * @param thisStart the start offset in this string.
 * @param string the other string.
 * @param start the start offset in {@code string}.
 * @param length the number of {@code char}s to compare.
 * @throws NullPointerException
 *             if {@code string} is {@code null}.
 */
public boolean regionMatches(int thisStart, String string, int start, int length) {
    if (string == null) {
        throw new NullPointerException("string == null");
    }
    if (start < 0 || string.count - start < length) {
        return false;
    }
    if (thisStart < 0 || count - thisStart < length) {
        return false;
    }
    if (length <= 0) {
        return true;
    }
    for (int i = 0; i < length; ++i) {
        if (charAt(thisStart + i) != string.charAt(start + i)) {
            return false;
        }
    }
    return true;
}


八、equals

比较字符串与其他对象,当且仅当另一个对象为string实例,且此对象表示相同的字符队列

/**
 * Compares the given object to this string and returns true if they are
 * equal. The object must be an instance of {@code String} with the same length,
 * where for every index, {@code charAt} on each string returns the same value.
 */
@Override public boolean equals(Object other) {
    if (other == this) {
      return true;
    }
    if (other instanceof String) {
        String s = (String)other;
        int count = this.count;
        if (s.count != count) {
            return false;
        }
        // TODO: we want to avoid many boundchecks in the loop below
        // for long Strings until we have array equality intrinsic.
        // Bad benchmarks just push .equals without first getting a
        // hashCode hit (unlike real world use in a Hashtable). Filter
        // out these long strings here. When we get the array equality
        // intrinsic then remove this use of hashCode.
        if (hashCode() != s.hashCode()) {
            return false;
        }
        for (int i = 0; i < count; ++i) {
            if (charAt(i) != s.charAt(i)) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}


九、equalsIgonreCase

忽略大小写比较字符串与其他对象,当且仅当另一个对象为string实例,且此对象表示相同的字符队列

/**
 * Compares the given string to this string ignoring case.
 *
 * <p>The strings are compared one {@code char} at a time. This is not suitable
 * for case-insensitive string comparison for all locales.
 * Use a {@link java.text.Collator} instead.
 */
@FindBugsSuppressWarnings("ES_COMPARING_PARAMETER_STRING_WITH_EQ")
public boolean equalsIgnoreCase(String string) {
    if (string == this) {
        return true;
    }
    if (string == null || count != string.count) {
        return false;
    }
    for (int i = 0; i < count; ++i) {
        char c1 = charAt(i);
        char c2 = string.charAt(i);
        if (c1 != c2 && foldCase(c1) != foldCase(c2)) {
            return false;
        }
    }
    return true;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值