Java程式訪問字串中的字元
在本文中,我們將使用Java中的charAt()方法訪問字串中的特定字元。該程式將演示如何查詢並在字串中指定位置顯示字元。
問題陳述
我們有一個字串,我們需要檢索給定位置的字元。例如,如果我們使用字串“laptop”,我們希望顯示位於第4個位置(基於0的索引)的字元。
輸入
"laptop"
輸出
String: laptop
Character at 4th position: t
訪問字串字元的步驟
以下是訪問字串字元的步驟:
- 首先,我們將定義字串“laptop”。
- 使用charAt()方法,並將所需位置作為引數(記住索引從0開始)。
- 列印結果以顯示指定位置的字元。
Java程式訪問字串中的字元
以下是一個訪問字串字元的示例:
public class Demo { public static void main(String[] args) { String str = "laptop"; System.out.println("String: "+str); // finding character at 4th position System.out.println("Character at 4th position: "+str.charAt(3)); } }
輸出
String: laptop Character at 4th position: t
程式碼解釋
在這個程式中,我們首先用值“laptop”初始化一個字串str。然後我們呼叫charAt(3)方法來檢索第4個位置(基於0的索引)的字元。charAt()方法返回指定索引處的字元,因此str.charAt(3)返回't',然後將其列印為輸出。
廣告