startswith()方法有两种变体。本文介绍了所有这些变体,如下所示:1.字符串startsWith():此方法测试字符串是否从第一个索引开始以指定的前缀开头。
Syntax public boolean startsWith(String prefix) 参数 prefix: the prefix to be matched. Return Value It returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise.
// Java code to demonstrate the
// working of startsWith()
public class Strt1 {
public static void main(String args[])
{
// Initialising String
String Str = new String("Welcome to geeksforgeeks");
// Testing the prefix using startsWith()
System.out.print("Check whether string starts with Welcome:");
System.out.println(Str.startsWith("Welcome"));
// Testing the prefix using startsWith()
System.out.print("Check whether string starts with geeks:");
System.out.println(Str.startsWith("geeks"));
}
}
输出:
Check whether string starts with Welcome:true Check whether string starts with geeks:false
2.字符串startsWith(String prefix,int strt_pos):此变体具有两个参数,并测试字符串是否以指定的前缀开头并以指定的索引开头。
Syntax public boolean startsWith(String prefix, int strt_pos) 参数 prefix:the prefix to be matched. strt_pos: where to begin looking in the string. Return Value It returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise.
// Java code to demonstrate the
// working of startsWith()
public class Strt2 {
public static void main(String args[])
{
// Initialising String
String Str = new String("Welcome to geeksforgeeks");
// Testing the prefix using startsWith()
System.out.print("Check whether string starts with Welcome at pos 11:");
System.out.println(Str.startsWith("Welcome", 11));
// Testing the prefix using startsWith()
System.out.print("Check whether string starts with geeks at pos 11:");
System.out.println(Str.startsWith("geeks", 11));
}
}
输出:
Check whether string starts with Welcome at pos 11:false Check whether string starts with geeks at pos 11:true
可能的应用:此方法主要可用于过滤前缀,例如。过滤以数字开头的电话号码或以特定字母开头的姓名。本文对此进行了解释。
// Java code to demonstrate the
// application of startsWith()
public class Appli {
public static void main(String args[])
{
// Initialising String
String Str = new String("Astha Tyagi");
// Testing the prefix using startsWith()
System.out.print("Check whether Astha Tyagi starts with A:");
System.out.println(Str.startsWith("A"));
}
}
输出:
Check whether Astha Tyagi starts with A:true
相关用法
- Java Java lang.Long.numberOfTrailingZeros()用法及代码示例
- Java Java lang.Long.reverse()用法及代码示例
- Java Java lang.Long.lowestOneBit()用法及代码示例
- Java Java lang.Long.byteValue()用法及代码示例
- Java Java lang.Long.builtcount()用法及代码示例
- Java Java lang.Long.highestOneBit()用法及代码示例
注:本文由纯净天空筛选整理自 Java.lang.String.startswith() in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。