Java程式遍歷字串的每個字元。
在本文中,我們將瞭解如何使用Java遍歷字串的每個字元。字串是一種資料型別,包含一個或多個字元,並用雙引號(“ ”)括起來。字元是一種資料型別,包含字母、整數或特殊字元。
問題陳述
編寫一個程式來遍歷字串的每個字元。以下是相同的演示:
輸入
The string is defined as: Java Program
輸出
The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
不同的方法
以下是遍歷字串中每個字元的不同方法:
使用for迴圈遍歷字串的每個字元
以下是使用for迴圈遍歷字串中每個字元的步驟:
- 定義一個字串變數input_string,其值為"Java Program"。
- 使用print語句列印定義的字串。
- 使用for迴圈遍歷字串的每個字元。
- 使用charAt()方法透過索引獲取字串的每個字元。
- 列印每個字元,後跟逗號。
- 列印所有字元後結束迴圈。
示例
以下是用for迴圈遍歷字串中每個字元的示例:
public class Characters { public static void main(String[] args) { String input_string = "Java Program"; System.out.println("The string is defined as: " +input_string); System.out.println("The characters in the string are: "); for(int i = 0; i<input_string.length(); i++) { char temp = input_string.charAt(i); System.out.print(temp + ", "); } } }
輸出
The string is defined as: Java Program The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
使用forEach迴圈遍歷字串的每個字元
以下是使用forEach迴圈遍歷字串中每個字元的步驟:
- 定義一個字串變數input_string,其值為"Java Program"。
- 使用print語句列印定義的字串。
- 使用toCharArray()方法將字串轉換為字元陣列。
- 使用forEach迴圈遍歷陣列中的每個字元。
- 列印每個字元,後跟逗號。
示例
以下是用forEach迴圈遍歷字串中每個字元的示例:
public class Main { public static void main(String[] args) { String input_string = "Java Program"; System.out.println("The string is defined as: " +input_string); System.out.println("The characters in the string are: "); for(char temp : input_string.toCharArray()) { System.out.print(temp + ", "); } } }
輸出
The string is defined as: Java Program The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
廣告