Java™ 教程(比較字符串和字符串的部分)

比較字符串和字符串的部分

String類有許多用於比較字符串和字符串部分的方法,下表列出了這些方法。正則表達式

方法 描述
boolean endsWith(String suffix)
boolean startsWith(String prefix)
若是此字符串以指定爲方法的參數的子字符串結束或以其開頭,則返回true
boolean startsWith(String prefix, int offset) 考慮從索引偏移量開始的字符串,若是它以指定爲參數的子字符串開頭,則返回true
int compareTo(String anotherString) 按字典順序比較兩個字符串;
返回一個整數,指示此字符串是否大於(結果 > 0),等於(結果 = 0)或小於(結果 < 0)參數。
int compareToIgnoreCase(String str) 按字典順序比較兩個字符串,忽略大小寫的差別;
返回一個整數,指示此字符串是否大於(結果 > 0),等於(結果 = 0)或小於(結果 < 0)參數。
boolean equals(Object anObject) 當且僅當參數是String對象時才返回true,該String對象表示與此對象相同的字符序列。
boolean equalsIgnoreCase(String anotherString) 當且僅當參數是String對象時才返回true,該對象表示與此對象相同的字符序列,忽略大小寫的差別。
boolean regionMatches(int toffset, String other, int ooffset, int len) 測試此字符串的指定區域是否與String參數的指定區域匹配。
區域的長度爲len,今後字符串的索引toffset開始,另外一個字符串的ooffset開始。
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 測試此字符串的指定區域是否與String參數的指定區域匹配。
區域的長度爲len,今後字符串的索引toffset開始,另外一個字符串的ooffset開始。
boolean參數指示是否應忽略大小寫;若是爲true,則在比較字符時忽略大小寫。
boolean matches(String regex) 測試此字符串是否與指定的正則表達式匹配,正則表達式在標題爲「正則表達式」的課程中討論。

如下程序RegionMatchesDemo使用regionMatches方法在另外一個字符串中搜索字符串:segmentfault

public class RegionMatchesDemo {
    public static void main(String[] args) {
        String searchMe = "Green Eggs and Ham";
        String findMe = "Eggs";
        int searchMeLength = searchMe.length();
        int findMeLength = findMe.length();
        boolean foundIt = false;
        for (int i = 0; 
             i <= (searchMeLength - findMeLength);
             i++) {
           if (searchMe.regionMatches(i, findMe, 0, findMeLength)) {
              foundIt = true;
              System.out.println(searchMe.substring(i, i + findMeLength));
              break;
           }
        }
        if (!foundIt)
            System.out.println("No match found.");
    }
}

這個程序的輸出是Eggs測試

程序逐步遍歷searchMe引用的字符串,對於每一個字符,程序調用regionMatches方法以肯定以當前字符開頭的子字符串是否與程序正在查找的字符串匹配。ui


上一篇:操縱字符串中的字符

下一篇:StringBuilder類

相關文章
相關標籤/搜索