Java 检查字符串开头
字符串是Java中的一个类,用于存储放在双引号内的一系列字符。这些字符实际上是String类型的对象。字符串类可在 ‘java.lang’ 包中使用。假设我们有一个字符串,并且我们的任务是找到该字符串的开头。我们假设开头是该字符串的前两个或三个字符。为了检查字符串开头,我们可以使用Java中提供的几个内置方法,包括substring()和charAt()。
Java程序检查字符串开头
我们可以使用以下方法来检查字符串开头:
- for循环
-
while循环
-
charAt()方法
-
substring()方法
在讨论这些方法之前,让我们通过一个示例来理解问题。
示例
输入:
String = "Tutorials Point";
输出
The beginning of given String is: Tu
示例1
在这个示例中,我们将初始化一个字符串,然后将字符串转换为字符数组,以便我们可以访问字符串的字符。最后,我们将使用for循环打印数组的前两个字符,即给定字符串的开头部分。
public class Example1 {
public static void main(String []args) {
// initializing the string
String str = "Tutorials Point";
// converting the string into character array
char strChars[] = str.toCharArray();
System.out.println("The given String is: " + str);
System.out.println("The beginning of given String is: ");
// loop to print beginning of the given string
for(int i = 0; i < 2; i++) {
System.out.print(strChars[i]);
}
}
}
输出
The given String is: Tutorials Point
The beginning of given String is:
Tu
示例2
我们还可以使用while循环来打印给定字符串的开头。在前一个示例的相同代码中,不使用for循环,改为使用while循环来检查字符串的开头。
public class Example2 {
public static void main(String []args) {
// initializing the string
String str = "Tutorials Point";
// converting the string into character array
char strChars[] = str.toCharArray();
System.out.println("The given String is: " + str);
System.out.println("The beginning of given String is: ");
// loop to print beginning of the given string
int i = 0;
while( i < 2 ) {
System.out.print(strChars[i]);
i++;
}
}
}
输出
The given String is: Tutorials Point
The beginning of given String is:
Tu
示例3
下面的示例说明了我们如何使用charAt()方法来检查字符串的开头。charAt()方法接受索引号作为参数,并返回指定位置处的字符串字符。
public class Example3 {
public static void main(String []args) {
// initializing the string
String str = "Tutorials Point";
System.out.println("The given String is: " + str);
// printing the beginning of string
System.out.println("The given String begins with: " + str.charAt(0));
}
}
输出
The given String is: Tutorials Point
The given String begins with: T
示例4
这是另一个Java程序,演示了如何检查给定字符串的开头。我们将使用substring()方法,该方法接受开始索引和结束索引作为参数,并返回这些索引之间的字符。
public class Example4 {
public static void main(String []args) {
// initializing the string
String str = "Tutorials Point";
System.out.println("The given String is: " + str);
// printing the beginning of string
System.out.println("The given String begins with: " + str.substring(0, 2));
}
}
输出
The given String is: Tutorials Point
The given String begins with: Tu
结论
我们从字符串的定义开始,接着在下一节中学习了如何检查给定字符串的开头。在我们讨论问题陈述时,我们发现可以使用四种不同的方式来找到字符串的开头,包括for循环、while循环、charAt()方法和substring()方法。