/**
* public boolean equals(Object anObject) {
* if (this == anObject) {
* return true;
* }
* if (anObject instanceof String) {
* String anotherString = (String) anObject;
* int n = value.length;
* if (n == anotherString.value.length) {
* char v1[] = value;
* char v2[] = anotherString.value;
* int i = 0;
* while (n-- != 0) {
* if (v1[i] != v2[i])
* return false;
* i++;
* }
* return true;
* }
* }
* return false;
*}
*
*
*/
//首先判斷str1是否爲null若是爲null,那就返回str2跟null比較的結果,若是不是null,那就調用str1.equals(str2)
public static boolean equals(String str1, String str2)
{
return str1 != null ? str1.equals(str2) : str2 == null;
}
//忽略字符串中大小寫,比較字符串是否相等
public static boolean equalsIgnoreCase(String str1, String str2)
{
return str1 != null ? str1.equalsIgnoreCase(str2) : str2 == null;
}
/**
*下面是String.java中indexOf方法的源碼
*這裏涉及到java低代理和高代理的知識,請自行百度。
* public int indexOf(int ch, int fromIndex) {
* final int max = value.length;
* if (fromIndex < 0) {
* fromIndex = 0;
* } else if (fromIndex >= max) {
* // Note: fromIndex might be near -1>>>1.
* return -1;
* }
* if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
* // handle most cases here (ch is a BMP code point or a
* // negative value (invalid code point))
* final char[] value = this.value;
* for (int i = fromIndex; i < max; i++) {
* if (value[i] == ch) {
* return i;
* }
* }
* return -1;
* } else {
* return indexOfSupplementary(ch, fromIndex);
* }
*}
*
*/
//這個函數很簡單,就是返回指定字符串中的指定字符首次出現的位置,沒有則返回-1,從0(即第一個字符開始)
public static int indexOf(String str, char searchChar)
{
if (isEmpty(str))
return -1;
else
return str.indexOf(searchChar);
}
//這個函數與上面函數相似,只不過是能夠本身設定開始查找指定字符的位置了,即fromIndex也就是下面的startPos
public static int indexOf(String str, char searchChar, int startPos)
{
if (isEmpty(str))
return -1;
else
return str.indexOf(searchChar, startPos);
}
//注意這個函數的兩個參數都是String類型
public static int indexOf(String str, String searchStr)
{
if (str == null || searchStr == null)
return -1;
else
return str.indexOf(searchStr);
}java