比较字符串 和部分字符串

String类具有许多用于比较字符串 和字符串 部分的方法。下表列出了这些方法。

比较字符串 的方法

MethodDescription
boolean endsWith(String suffix) boolean startsWith(String prefix)如果此字符串 以指定为方法参数的子字符串 结尾或开头,则返回true
boolean startsWith(String prefix, int offset)考虑以索引offset开头的字符串,如果以指定为参数的子字符串 开头,则返回true
int compareTo(String anotherString)按字典 Sequences 比较两个字符串。返回一个整数,该整数指示此字符串 是否大于(结果> 0),等于(结果= 0)还是小于(结果<0)参数。
int compareToIgnoreCase(String str)按字典 Sequences 比较两个字符串,忽略大小写差异。返回一个整数,该整数指示此字符串 是否大于(结果> 0),等于(结果= 0)还是小于(结果<0)参数。
boolean equals(Object anObject)当且仅当参数是一个String对象(表示与此对象相同的字符序列)时,返回true
boolean equalsIgnoreCase(String anotherString)当且仅当参数是一个String对象(表示与此对象相同的字符序列)时才返回true,忽略大小写的差异。
boolean regionMatches(int toffset, String other, int ooffset, int len)测试此字符串 的指定区域是否与 String 参数的指定区域匹配。


区域的 Long 度为len,并从该字符串 的索引toffset开始,对于另一个字符串 的索引为ooffset
| boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) |测试此字符串 的指定区域是否与 String 参数的指定区域匹配。
区域的 Long 度为len,此字符串 的起始位置为索引toffset,其他字符串 的起始位置为ooffset
布尔参数指示是否应忽略大小写;如果为 true,则在比较字符时忽略大小写。
| boolean matches(String regex) |测试此字符串 是否与指定的正则表达式匹配。在标题为“正则表达式”的类中讨论了正则表达式。

以下程序RegionMatchesDemo使用regionMatches方法在另一个字符串 中搜索一个字符串:

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 方法来确定以当前字符开头的子字符串 是否与程序正在寻找的字符串 匹配。