Java String startsWith()方法

Java String类的startsWith()方法用于检查字符串是否以指定的前缀开始。如果字符串以给定的前缀开始,则返回true;否则返回false。

语法

startsWith()方法的语法如下:

public boolean startsWith(String prefix)  
public boolean startsWith(String prefix, int offset)  

参数

prefix:要检查的字符序列,即前缀。

返回值

如果字符串以前缀开始,则返回true;否则返回false。

startsWith(String prefix, int toffset)的内部实现

// 由于在这种类型的 startWith() 方法中未提及偏移量,因此偏移量是
// 视为 0.  
public boolean startsWith(String prefix)   
{  
// the offset is 0  
return startsWith(prefix, 0);  
}  

Java String startsWith()方法示例

startsWith()方法区分字符的大小写。请看下面的示例:

文件名:StartsWithExample.java

public class StartsWithExample  
{    
// main method  
public static void main(String args[])  
{    
// input string  
String s1="java string split method by javatpoint";    
System.out.println(s1.startsWith("ja"));  // true  
System.out.println(s1.startsWith("java string"));   // true  
System.out.println(s1.startsWith("Java string"));  // false as 'j' and 'J' are different   
}  
}    

输出:

true
true
false

Java String startsWith(String prefix, int offset)方法示例

这是startWith()方法的重载方法,用于向函数传递额外的参数(偏移量)。该方法从传递的偏移量开始工作。让我们看一个示例。

文件名:StartsWithExample2.java

public class StartsWithExample2 {    
    public static void main(String[] args) {    
        String str = "Javatpoint";    
        // 没有提到抵消;因此,在这种情况下偏移量为 0.  
        System.out.println(str.startsWith("J")); // True    
  
         // 没有提到抵消;因此,在这种情况下偏移量为 0.  
        System.out.println(str.startsWith("a")); // False   
        // offset is 1  
        System.out.println(str.startsWith("a",1)); // True    
    }    
}    

输出:

true
false
true

Java String startsWith()方法示例 - 3

如果我们在字符串的开头添加一个空字符串,则对字符串没有任何影响。

"" + "Tokyo Olympics" = "Tokyo Olympics"

这意味着可以说Java中的字符串总是以空字符串开始。让我们通过Java代码来确认这一点。

文件名:StartsWithExample3.java

public class StartsWithExample3   
{  
// main method  
public static void main(String argvs[])  
{  
// input string  
String str = "Tokyo Olympics";  
  
if(str.startsWith(""))  
{  
System.out.println("The string starts with the empty string.");  
}  
else  
{  
System.  
out.println("The string does not start with the empty string.");     
}  
  
}  
}  

输出:

The string starts with the empty string.

标签: java, Java面试题, Java下载, java教程, java技术, Java学习, Java学习教程, Java语言, Java开发, Java入门教程, Java进阶教程, Java高级教程, Java笔试题, Java编程思想