Android关于String数据的startsWith()和endsWith()函数操作

本文介绍了Java中用于字符串前缀和后缀判断的方法startsWith()和endsWith()。通过源码解析了这两个方法的工作原理,并提供了多个示例帮助理解。

本文链接:http://blog.youkuaiyun.com/qq_16628781/article/details/49337619   


知识点:

1、Java函数startsWith()简介及用法;

2、Java函数endsWith()简介及用法;


有很多时候我们需要某个字串进行前缀或者是后缀的判断,例如在webView中加载一个网页,但是不是我们所要的那个网页,或者是进行某些字段的“拦截”功能,依据判断前缀或者是后缀来归类文件,文件夹等等操作。

   下面来介绍两个常用到的函数,他们都是String类里面的函数,直接new一个对象就可以调用了,或者是直接一个字串.就可以调用了。不多说了,先从源码的角度解释函数。

      

 /**
     * Compares the specified string to this string to determine if the
     * specified string is a prefix.
     *
     * @param prefix
     *            the string to look for. 给定的字串
     * @return {@code true} if the specified string is a prefix of this string,
     *         {@code false} otherwise 返回布尔值
     * @throws NullPointerException
     *             if {@code prefix} is {@code null}.
     */
//解释:给定的字串和自己定义的字串相比较,看是否是前缀相同。eg:A.startsWith(B),A是给定的
//B是自己定义的字串
    public boolean startsWith(String prefix) {
        return startsWith(prefix, 0);
    }


当然它并不孤单,还有一个同父异母的长兄:

   

 /**
     * Compares the specified string to this string, starting at the specified
     * offset, to determine if the specified string is a prefix.
     *
     * @param prefix
     *            the string to look for.
     * @param start
     *            the starting offset.
     * @return {@code true} if the specified string occurs in this string at the
     *         specified offset, {@code false} otherwise.返回布尔值
     * @throws NullPointerException
     *             if {@code prefix} is {@code null}.
     */
//解释:指定字串和定义的字串从指定的start位置开始比较是否前缀相同。
//eg:A.startsWith(B,C),看A是否和B从C位置开始是否前缀相同,A为指定字串,B为定义字串
    public boolean startsWith(String prefix, int start) {
        return regionMatches(start, prefix, 0, prefix.count);
    }



示例eg:

        String str1 = "this is str1";
        String str2 = "this is str2";
        if (str1.startsWith(str2)) {
            System.out.println("===>>yes=" + str1.startsWith(str2));
        } else {
            System.out.println("===>>no=" + str1.startsWith(str2));
        }
//结果:===>>no=false 最后的字符不同,空格也表示相同


        String str1 = "this is str1";
        String str2 = "this i";
        if (str1.startsWith(str2)) {
            System.out.println("===>>yes=" + str1.startsWith(str2));
        } else {
            System.out.println("===>>no=" + str1.startsWith(str2));
        }
//结果是:===>>yes=true ,空格而是算前缀的一个,有空格处也相等。


        String str1 = "this is str1";
        String str2 = "t";
        if (str1.startsWith(str2)) {
            System.out.println("===>>yes=" + str1.startsWith(str2));
        } else {
            System.out.println("===>>no=" + str1.startsWith(str2));
        }

//结果:===>>yes=true ,同样一个字母t也是算共同的浅醉;

	
        String str1 = "this is str1";
        String str2 = "tH";
        if (str1.startsWith(str2)) {
            System.out.println("===>>yes=" + str1.startsWith(str2));
        } else {
            System.out.println("===>>no=" + str1.startsWith(str2));
        }
//结果:===>>no=false 看,它还区分大小写。

   最后,还没有完,我们看了前缀的比较,那有没有后缀做比较的呢?答案是有的。我们来看看。

    /**
     * Compares the specified string to this string to determine if the
     * specified string is a suffix.
     *
     * @throws NullPointerException
     *             if {@code suffix} is {@code null}.
     */
//解释:比较指定字串和定义字串的后缀是否相等。返回布尔值类型。
    public boolean endsWith(String suffix) {
        return regionMatches(count - suffix.count, suffix, 0, suffix.count);
    }

   因为这个和startsWith()用法差不多,这里就不给出示例了,大家可以多去尝试下。

   谢谢大家!



### Java 中 `startsWith` `endsWith` 方法详解 #### 方法定义与基本用法 在 Java 中,字符串类提供了两个非常有用的方法来检查字符串是否以特定前缀或后缀开头或结尾:`startsWith` `endsWith`。 对于任意给定的字符串对象 `"abcd"`: - 调用 `str.startsWith("ab")` 将返回布尔值 `true` 表明该字符串确实是以子串 `"ab"` 开始[^2]。 - 类似地,调用 `str.endsWith("cd")` 返回的结果也是 `true`,表示此字符串结束于指定序列 `"cd"`。 这些操作可以帮助开发者快速判断字符串的内容特征而无需执行更复杂的模式匹配算法。 #### 忽略大小写的比较方式 当需要不区分大小写来进行上述两种检测时,在标准库中并没有直接提供带有参数控制大小写的版本。但是可以通过转换整个待测字符串以及目标前后缀至统一的小写字母形式再做对比实现这一需求[^1]。 ```java public class StringCaseInsensitiveCheck { public static boolean startsWithIgnoreCase(String str, String prefix) { if (prefix == null || str == null) return false; if (prefix.isEmpty()) return true; int plen = prefix.length(); return plen <= str.length() && prefix.equalsIgnoreCase(str.substring(0, plen)); } public static void main(String[] args){ System.out.println(startsWithIgnoreCase("HelloWorld", "hello")); // 输出: true } } ``` 这段代码展示了如何创建自定义函数 `startsWithIgnoreCase()` 来完成忽略大小写的前缀匹配任务。通过使用 `equalsIgnoreCase()` 函数可以有效地处理不同字母大小写的情况。 同样适用于 `endsWith` 的情况也可以按照相同思路构建相应逻辑。 #### 单元测试中的应用实例 为了验证程序行为是否符合预期,可以在编写自动化测试案例时利用 JUnit 提供的强大工具集。例如下面的例子就展示了一个简单的断言语句用于确认某个被测试变量的确切起始部分[^3]: ```java import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; @Test public void testStartAndEnd(){ String testedString = "developerWorks"; assertThat(testedString, startsWith("developer")); assertThat(testedString, endsWith("orks")); } ``` 这里运用了 Hamcrest 库里的 matchers 结合 JUnit 断言机制实现了更加简洁易读的表达式结构。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值