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

Chương trình Java để sắp xếp một chuỗi

Trong bài này, chúng ta sẽ hiểu cách sắp xếp 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 là một chuỗi các ký 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à -

Input string: javaprogram

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

String after sorting is: [a, a, a, g, j, m, o, p, r, r, v]

Thuật toán

Step 1 - START
Step 2 - Declare a string value namely input_string, a character array charArray, char value name temp and an int value namely string_size.
Step 3 - Define the values.
Step 4 - Assign the string to the character array.
Step 5 - Iterate over the elements of the character array twice, check if the adjacent elements are ordered, if not, swap them using temp variable.
Step 6 - Display the sorted array
Step 7 - 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".

import java.util.Arrays;
public class SortString {
   public static void main(String args[]) {
      int temp, string_size;
      String input_string = "javaprogram";
      System.out.println("The string is defined as: " +input_string);
      char charArray[] = input_string.toCharArray();
      string_size = charArray.length;
      for(int i = 0; i < string_size; i++ ) {
         for(int j = i+1; j < string_size; j++) {
            if(charArray[i]>charArray[j]) {
               temp = charArray[i];
               charArray[i] = charArray[j];
               charArray[j] = (char) temp;
            }
         }
      }
      System.out.println("\nThe characters of the string after sorting is: "+Arrays.toString(charArray));
   }
}

Đầu ra

The string is defined as: javaprogram

The characters of the string after sorting is: [a, a, a, g, j, m, o, p, r, r, v]

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.

import java.util.Arrays;
public class SortString {
   static void sort(string input_string){
      int temp, string_size;
      char charArray[] = input_string.toCharArray();
      string_size = charArray.length;
      for(int i = 0; i < string_size; i++ ) {
         for(int j = i+1; j < string_size; j++) {
            if(charArray[i]>charArray[j]) {
               temp = charArray[i];
               charArray[i] = charArray[j];
               charArray[j] = (char) temp;
            }
         }
      }
      System.out.println("\nThe characters of the string after sorting is: "+Arrays.toString(charArray));
   }
   public static void main(String args[]) {
      String input_string = "javaprogram";
      System.out.println("The string is defined as: " +input_string);
      sort(input_string);
   }
}

Đầu ra

The string is defined as: javaprogram

The characters of the string after sorting is: [a, a, a, g, j, m, o, p, r, r, v]