如何检查字符串是否以特定子字符串开头 Java?


String 类可以用于表示字符字符串,Java 程序中的所有字符串文本都作为 String 类的实例实现。字符串是常量,一旦创建,就不能更改它们的值(不可变)。

我们可以使用 String 类的 startsWith() 方法来检查一个字符串是否以一个特定的字符串开头,它会返回一个布尔值,真或假。

语法

public boolean startsWith(String prefix)

示例

Open Compiler
public class StringStartsWithSubStringTest { public static void main(String[] args) { String str = "WelcomeToTutorialsPoint"; if(str.startsWith("Welcome")) { System.out.println("Begins with the specified word!"); } else { System.out.println("Does not begin with the specified word!"); } } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

Begins with the specified word!

更新于: 2023 年 12 月 1 日

1K+ 浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告