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()方法。
廣告