6.2.3、字符串和字符串子串的比较

本文介绍了Java的String类中用于比较字符串和子串的方法,通过示例展示了如何使用regionMatches方法进行搜索和匹配操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇Java教程基于JDK1.8。教程中的示例和实践不会使用未来发行版中的优化建议。
字符串和字符串子串的比较

String 类提供了许多方法来比较字符串和子串。下表列出了这些方法:

方法描述
boolean endsWith(String suffix)
boolean startsWith(String prefix)
如果字符串以给定的suffix开头或结尾,则返回true
boolean startsWith(String prefix, int offset)以下标offset开头的字符串,如果前缀是prefix,则返回true
int compareTo(String anotherString)按词法比较两个字符串。返回整数来表示当前字符串比参数大(结果大于0),与参数相等(结果等于0),比参数小(结果小于0)
int compareToIgnoreCase(String str)同int compareTo(String anotherString),但忽略大小写
boolean equals(Object anObject)当参数是个String对象并且包含的字符序列与当前对象一致则返回true
boolean equalsIgnoreCase(String anotherString)同boolean equals(Object anObject) ,忽略大小写
boolean regionMatches(int toffset, String other, int ooffset, int len)测试此字符串的指定区域是否与字符串参数的指定区域匹配。区域的长度为len,从这个字符串的索引toffset开始,另一个字符串的索引从ooffset开始。
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)同上,忽略大小写
boolean matches(String regex)测试该字符串是否匹配给定的正则表达式

下面的程序,使用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方法来判断当前子串是否以该字符开头并匹配程序正在找的字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值