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循环来打印给定字符串的开头。在前面的示例代码中,我们将使用while循环代替for循环来检查字符串的开头。
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()方法。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP