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

Chương trình Java để đảo ngược một chuỗi

Trong bài này, chúng ta sẽ hiểu cách đảo ngược một 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 (“”). Chuỗi ngược đang hiển thị chuỗi ngược hoặc từ phải sang trái.

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 reversed string is: margorP avaJ

Thuật toán

Step 1 - START
Step 2 - Declare two string values namely input_string and reverse_string, and a char value namely temp.
Step 3 - Define the values.
Step 4 - Iterating using a for-loop, assign the i’th character to temp and later assign the ‘temp + reverse_string’ to reverse_string value. I.e adding the first element of the string to the last position of the reverse_string. Store the value.
Step 5 - Display the result
Step 6 - Stop

Ví dụ 1

Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "main".

public class ReverseString {
   public static void main (String[] args) {
      String input_string= "Java Program", reverse_string="";
      char temp;
      System.out.println("The string is defined as: " + input_string);
      for (int i=0; i<input_string.length(); i++) {
         temp= input_string.charAt(i);
         reverse_string= temp+reverse_string;
      }
      System.out.println("\nThe reversed string is: "+ reverse_string);
   }
}

Đầu ra

The string is defined as: Java Program

The reversed string is: margorP avaJ

Ví dụ 2

Ở đây, chúng tôi đóng gói các hoạt động thành các hàm thể hiện lập trình hướng đối tượng.

public class ReverseString {
   static void reverse(String input_string){
      String reverse_string = "";
      char temp;
      for (int i=0; i<input_string.length(); i++) {
         temp= input_string.charAt(i);
         reverse_string= temp+reverse_string;
      }
      System.out.println("\nThe reversed string is: "+ reverse_string);
   }
   public static void main (String[] args) {
      String input_string= "Java Program";
      System.out.println("The string is defined as: " + input_string);
      reverse(input_string);
   }
}

Đầu ra

The string is defined as: Java Program

The reversed string is: margorP avaJ