原文: https://beginnersbook.com/2013/12/java-string-startswith-method-example/

字符串类startsWith()方法用于检查字符串的前缀。它根据给定的字符串是否以指定的字母或单词开头,返回布尔值truefalse

例如:

  1. String str = "Hello";
  2. //This will return true because string str starts with "He"
  3. str.startsWith("He");

Java String startsWith()方法

StarsWith()方法有两种变体。

boolean startsWith(String str):如果String strString的前缀,则返回true

boolean startsWith(String str, index fromIndex):如果Stringstr开头,则返回true,它从指定的索引fromIndex开始查找。例如,假设String s的值是"Hi there",我们调用这样的starsWith()方法 - s.startsWith("there", 3)然后这将返回true,因为我们已经将值 3 作为fromIndex传递,搜索关键字"there"从给定字符串s的索引 3 开始,并在字符串s的开头找到。

startsWith()方法的一个简单示例

这是一个简单的例子,我们有一个字符串s,我们正在使用startsWith()方法检查字符串s是否以特定的单词开头。

  1. public class JavaExample{
  2. public static void main(String args[]){
  3. //given string
  4. String s = "This is just a sample string";
  5. //checking whether the given string starts with "This"
  6. System.out.println(s.startsWith("This"));
  7. //checking whether the given string starts with "Hi"
  8. System.out.println(s.startsWith("Hi"));
  9. }
  10. }

输出:

Java `String startsWith()`方法 - 图1

Java String startsWith()方法示例

让我们举一个例子,我们使用startsWith()方法的两种变体。

  1. public class StartsWithExample{
  2. public static void main(String args[]) {
  3. String str= new String("quick brown fox jumps over the lazy dog");
  4. System.out.println("String str starts with quick: "+str.startsWith("quick"));
  5. System.out.println("String str starts with brown: "+str.startsWith("brown"));
  6. System.out.println("substring of str(starting from 6th index) has brown prefix: "
  7. +str.startsWith("brown", 6));
  8. System.out.println("substring of str(starting from 6th index) has quick prefix: "
  9. +str.startsWith("quick", 6));
  10. }
  11. }

输出:

  1. String str starts with quick: true
  2. String str starts with brown: false
  3. substring of str(starting from 6th index) has brown prefix: true
  4. substring of str(starting from 6th index) has quick prefix: false