Java String startsWith()方法

培训教学 潘老师 8个月前 (09-04) 199 ℃ (0) 扫码查看

Java String.startsWith() 方法用于检查一个字符串是否以指定的前缀子字符串开头。参数 prefix 必须是一个标准的子字符串,不支持正则表达式。

String.startsWith() API

startsWith() 方法是一个重载方法,有两种形式:

  • boolean startsWith(substring) – 如果子字符串是字符串的前缀,则返回 true。
  • boolean startsWith(substring, fromIndex) – 如果字符串从指定的索引 fromIndex 开始以子字符串开头,则返回 true。

String.startsWith(substring) 示例

以下的 Java 程序检查一个字符串是否以指定的前缀开头。

String blogName = "panziye.com";
Assertions.assertTrue(blogName.startsWith("pan"));
Assertions.assertTrue(blogName.startsWith("panziye"));
Assertions.assertFalse(blogName.startsWith("ziye"));

不支持正则表达式

请注意,startsWith() 方法不支持将正则表达式作为参数。如果我们将正则表达式作为参数传递,它将被视为普通字符串处理。

String blogName = "panziye.com";
Assertions.assertFalse(blogName.startsWith("^p"));

如果你想要使用正则表达式来检查前缀,那么可以使用 Pattern 和 Matcher API

不支持Null

请注意,不允许将 null 作为方法参数。如果传递了 null,该方法将抛出 NullPointerException 异常。

Assertions.assertThrows(NullPointerException.class, () -> {
  blogName.startsWith(null);
});

String.startsWith(substring, fromIndex)示例

startsWith(substring, fromIndex) 方法也检查子字符串前缀,但不同之处在于它使用 fromIndex 参数指定的索引位置开始检查前缀。

同样,该方法也不接受 null 作为参数。如果传递了 null,将会抛出异常。

String blogName = "panziye.com";
Assertions.assertTrue(blogName.startsWith("p", 0));
Assertions.assertFalse(blogName.startsWith("ye", 0));
Assertions.assertTrue(blogName.startsWith("zi", 3));

版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/teach/8669.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】