Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để Lặp lại qua từng ký tự của chuỗi.

Trong bài này, chúng ta sẽ hiểu cách lặp qua từng ký tự của chuỗi. Chuỗi là một kiểu dữ liệu chứa một hoặc nhiều ký tự và được đặt trong dấu ngoặc kép (“”). Char là một kiểu dữ liệu có chứa một bảng chữ cái hoặc một số nguyên hoặc một ký tự đặc biệt.

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

The string is defined as: Java Program

Đầu ra mong muốn sẽ là -

The characters in the string are:
J, a, v, a, , P, r, o, g, r, a, m,

Thuật toán

Step 1 - START
Step 2 - Declare a string namely input_string, a char namely temp.
Step 3 - Define the values.
Step 4 - Iterate over the string, print each character at index ‘i’ of the string along with a blank space.
Step 5 - Display the result
Step 6 - Stop

Ví dụ 1

Đây, vòng lặp 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 + ", ");
      }
   }
}

Đầu ra

The string is defined as: Java Program
The characters in the string are:
J, a, v, a, , P, r, o, g, r, a, m,

Ví dụ 2

Đây, cho từng vòng lặp.

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 + ", ");
      }
   }
}

Đầu ra

The string is defined as: Java Program
The characters in the string are:
J, a, v, a, , P, r, o, g, r, a, m,