Home  >  Article  >  Java  >  How to implement alphabetical sorting in strings in java

How to implement alphabetical sorting in strings in java

PHPz
PHPzforward
2023-05-16 12:49:061671browse

Question requirements

Java implements alphabetical sorting in strings and outputs the sorted results

Analysis

1. Create a string, assign a value and Store characters into an array one by one.

String str = "chenughonghuiaikuangwantong1314";
    char[] chars = str.toCharArray();

2. Sort it

The sort method is a static method in the Arrays class and can be called directly using the class name.

static void sort(type [] a)
  • Sort the specified type array in ascending numerical order.

  • The default is ascending order

static void sort(type [] a, int fromIndex, int toIndex)

Sort the specified range of the specified array in ascending numerical order.

  • type can be specified as int, float, double, long, byte, etc.

  • ##a - The array to be sorted

  • fromIndex - The index of the first element to be sorted (inclusive)

  • toIndex-The index of the last element to be sorted (exclusive)

3. Print the loop through the for loop

Forward printing

for (int i = 0; i < chars.length; i++) {
        System.out.print(chars[i]);
    }

Reverse printing

for (int i = chars.length - 1; i >= 0; i--) {
        System.out.print(chars[i]);
    }

java code

import java.util.Arrays;

public class characterSorting {
    public static void main(String[] args) {
        String str = "chenughonghuiaikuangwantong1314";
        System.out.println("原字符串:"+str);
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        //正序遍历输出
        System.out.println("正序输出:");
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i]);
        }
        //倒序遍历输出
        System.out.println();
        System.out.println("倒序输出:");
        for (int i = chars.length - 1; i >= 0; i--) {
            System.out.print(chars[i]);
        }
    }
}

Running result

How to implement alphabetical sorting in strings in java

Remember to write first psvm! ! ! ! ! ! (I made a mistake here by 0.0)

The above is the detailed content of How to implement alphabetical sorting in strings in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete