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方法在另一个字符串中搜索字符串:

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


上一篇:操纵字符串中的字符
下一篇:StringBuilder类
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值