Home > Java > javaTutorial > body text

How to implement alphabetical sorting in strings in java

PHPz
Release: 2023-05-16 12:49:06
forward
1705 people have browsed it

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();
Copy after login

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)
Copy after login
  • Sort the specified type array in ascending numerical order.

  • The default is ascending order

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

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]);
    }
Copy after login

Reverse printing

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

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]);
        }
    }
}
Copy after login
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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!