文档

Java™ 教程
隐藏目录
比较字符串和字符串的部分
目录:学习Java语言
课程:数字和字符串
部分:字符串

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

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

比较字符串的方法
方法 描述
boolean endsWith(String suffix)
boolean startsWith(String prefix)
如果此字符串以指定的子字符串结尾或以指定的子字符串开头,则返回true
boolean startsWith(String prefix, int offset) 从索引offset处开始考虑字符串,并返回如果以指定的子字符串开头,则返回true
int compareTo(String anotherString) 按字典顺序比较两个字符串。返回一个整数,指示此字符串是否大于(结果为> 0)、等于(结果为= 0)或小于(结果为< 0)参数。
int compareToIgnoreCase(String str) 按字典顺序比较两个字符串,忽略大小写差异。返回一个整数,指示此字符串是否大于(结果为> 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参数的指定区域匹配。

区域长度为len,在此字符串的索引toffset处开始,另一个字符串的索引ooffset处开始。

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 测试此字符串的指定区域是否与String参数的指定区域匹配。

区域长度为len,在此字符串的索引toffset处开始,另一个字符串的索引ooffset处开始。

布尔参数指示是否应忽略大小写;如果为true,则比较字符时忽略大小写。

boolean matches(String regex) 测试此字符串是否与指定的正则表达式匹配。正则表达式在名为“正则表达式”的课程中讨论。

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

public class RegionMatchesDemo {
    public static void main(String[] args) {
        String searchMe = "绿色鸡蛋和火腿";
        String findMe = "鸡蛋";
        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("未找到匹配项。");
    }
}

这个程序的输出是 鸡蛋

程序逐个字符遍历 searchMe 引用的字符串。对于每个字符,程序调用 regionMatches 方法来确定从当前字符开始的子字符串是否与程序正在查找的字符串匹配。


上一页: 操作字符串中的字符
下一页: StringBuilder类