This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Like it and see. Make it a habit. Wechat search [a coding] follow this programmer who is struggling in the Internet.

This article is included in the technical expert training, which contains my learning route, series of articles, interview question bank, self-study materials, e-books, etc. Welcome to star ⭐ ️

Topic describes

Difficulty: Easy

Order the following strings alphabetically: “door”,”apple”,” apple”,” dooe”,”boy”

Example output:

Apple
apple
boy
dooe
door
Copy the code

knowledge

  • Double loop
  • compareTo()

Their thinking

We use the for loop for bit-by-bit comparison, but unlike numbers, strings can be compared directly. Instead of converting them to char for comparison, we can also use compareTo().

The compareTo() method is used to compare two ways:

  • A string is compared to an object.
  • Compares two strings in lexicographical order.

The return value is an integer that compares the size of the corresponding characters (ASCII order). If the first character and the first character of the argument are not equal, the comparison ends and the difference between them is returned. If the first character and the first character of the argument are equal, the second character and the second character of the argument are compared. And so on until one of the characters being compared or compared ends.

  • If the argument string is equal to this string, the value 0 is returned;
  • If the string is less than the string argument, a value less than 0 is returned;
  • If the string is greater than the string argument, a value greater than 0 is returned.

Code implementation

/** * List several strings in lexicographical order * a coding */
public class question_16 {
    public static void main(String[] args) {
        String a[]={"door"."apple"."Apple"."dooe"."boy"};
        for(int i=0; i<a.length-1; i++) {for(int j=i+1; j<a.length; j++) {if(a[j].compareTo(a[i])<0) { String temp=a[i]; a[i]=a[j]; a[j]=temp; }}}for(int i=0; i<a.length; i++) { System.out.print(a[i]+"\n"); }}}Copy the code

The output

Expand the summary

In Java8, the sort() method with the new stream feature might make sorting easier.

The last

One foot is difficult to go, one hand is difficult to sing, a person’s power is limited after all, a person’s journey is doomed to be lonely. When you set a good plan, with full of blood ready to set out, must find a partner, and Tang’s monk to the West, the master and his disciples four people united as one to pass the ninety-eight difficult. So,

If you want to learn Java well

Want to go to company

Want to get high salary

Want to have a group of like-minded partners

Please join the technical exchange