Java 根据长度对数组中的字符串进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19213788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:06:54  来源:igfitidea点击:

Sort strings in an array based on length

javaalgorithmsorting

提问by

I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?

我有以下基于长度对字符串进行排序的程序。我想先打印最短的元素。我不想使用 Comparator 或任何 API 来做到这一点。我哪里出错了?

public class SortArrayElements {
    public static void main(String[] args) {
        String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
        String[] sortedArr = new String[arr.length];

        for(int i=0;i<sortedArr.length;i++)
        {           
            sortedArr[i] = compareArrayElements(arr);                       
        }

        System.out.println("The strings in the sorted order of length are: ");
        for(String sortedArray:sortedArr)
        {
            System.out.println(sortedArray);
        }
    }

    public static String compareArrayElements(String[] arr) {
        String temp = null;
        for(int i=0;i<arr.length-1;i++)
        {
            temp = new String();
            if(arr[i].length() > arr[i+1].length())
                temp = arr[i+1];
            else
                temp = arr[i];
        }
        return temp;
    }
}

采纳答案by TwoThe

If you really want to learn Java: use a Comparator. Any other way is bad Java code.

如果你真的想学习 Java:使用比较器。任何其他方式都是糟糕的 Java 代码。

You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.

但是,您可以根据需要重写 Comparator 系统,它会教您正确的代码结构。

For your actual code, here are some hints:

对于您的实际代码,这里有一些提示:

  • Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.

  • Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".

  • Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.

  • You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
  • 使用正确的算法比用于编码的语言重要得多。无论使用何种语言,好的算法总是相同的。

  • 永远不要在循环中执行 new ,除非您确实需要创建新对象。GC 说“谢谢”。

  • 更改 compareArrayElements 函数以接受最小大小并让它返回至少具有最小大小的最小字符串。

  • 您可以删除您认为最小的那些字符串(将它们设置为 null),但这会修改​​原始数组。

回答by GGrec

Use bubble sort, but instead of comparing ints, just compare Stringlengths.

使用冒泡排序,但不是比较ints,而是比较String长度。

I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.

我不会为你写代码。您将不得不对该算法进行一些研究。作为程序员,谷歌是你最好的朋友。

Good luck.

祝你好运。

References:

参考:

回答by Hymanson

Implement bubbleSort()and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.

实施bubbleSort()swap()。我的实现改变了原始数组,但如果需要,您可以修改它们以制作副本。

public class SortArrayElements {
    public static void main(String[] args) {
        String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
        bubbleSort(arr);

        System.out.println("The strings in the sorted order of length are: ");
        for (String item : arr) {
            System.out.println(item);
        }

    }

    // Mutates the original array
    public static void bubbleSort(String[] arr) {
        boolean swapped = false;
        do {
            swapped = false;
            for (int i = 0; i < arr.length - 1; i += 1) {
                if (arr[i].length() > arr[i + 1].length()) {
                    swap(arr, i, i + 1);
                    swapped = true;
                }
            }
        } while (swapped);
    }

    // Mutates the original array
    public static void swap(String[] arr, int index0, int index1) {
        String temp = arr[index0];
        arr[index0] = arr[index1];
        arr[index1] = temp;
    }
}

回答by kuldip phadatare

//sort String array based on length 

public class FirstNonRepeatedString {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.println("Please Enter your String");
        String str = in.nextLine();
        String arrString[] = str.split("\s"); 
        arrString = sortArray(arrString);
        System.out.println("Sort String ");
        for(String s:arrString){
            System.out.println(s);
        }
    }

    private static String[] sortArray(String[] arrString) {
        int length = arrString.length;
            String s;
            for (int i = 0; i < length ; i++) {
                s= new String();

              for(int j = 0; j < length; j++ ){
                  if(arrString[i].length()< arrString[j].length()){
                      s = arrString[i];
                      arrString[i] = arrString[j];
                      arrString[j] = s;
                  }
              }
            }

        return arrString;
    }
}

回答by Gourav

Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string

好的,代码完全基于循环和冒泡排序。没有你想要的套装。这是一个纯循环程序,因此您可以理解嵌套循环,而且它不会更改索引或字符串的某些内容

      import java.util.*;

    class strings {
    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    ArrayList<String> a = new ArrayList<String>(2);
    System.out.println("Start entering your words or sentences.");
    System.out.println("Type stop to stop.");
    String b;
    int c = 0, d;

    do {
        b = in.nextLine();
        b = b.trim();
        a.add(b);
        c++;
    }
    while (!b.equalsIgnoreCase("stop"));
    if (c > 1)
        a.remove(a.size() - 1);


    System.out.println("Choose the sort you want. Type the corresponding 
    number");
    System.out.println("1. Ascending");
    System.out.println("2. Descending");
    int sc=in.nextInt();
    switch(sc) {

        case 1: {
            int sag[] = new int[a.size()];

            for (int jk = 0; jk < a.size(); jk++) {
                b = a.get(jk);
                c = b.length();
                sag[jk] = c;
            }
            int temp;
            for (int i = 0; i < a.size() - 1; i++) {
                for (int j = 0; j < a.size() - 1; j++) {
                    if (sag[j] > sag[j + 1]) {
                        temp = sag[j + 1];
                        sag[j + 1] = sag[j];
                        sag[j] = temp;
                    }
                }
            }
            ArrayList saga = new ArrayList();
            for (int i = 0; i < sag.length; i++) {
                saga.add(sag[i]);

            }
            for (int i = 0; i < saga.size(); i++) {

                for (int j = i + 1; j < saga.size(); j++) {
                    if (saga.get(i).equals(saga.get(j))) {
                        saga.remove(j);
                        j--;
                    }
                }

            }


            for (int i = 0; i < saga.size(); i++) {
                for (int j = 0; j < a.size(); j++) {
                    String jl = a.get(j);
                    if (saga.get(i).equals(jl.length()))
                        System.out.println(jl);
                }
            }
            break;
        }
        case 2: {
            int sag[] = new int[a.size()];

            for (int jk = 0; jk < a.size(); jk++) {
                b = a.get(jk);
                c = b.length();
                sag[jk] = c;
            }
            int temp;
            for (int i = 0; i < a.size() - 1; i++) {
                for (int j = 0; j < a.size() - 1; j++) {
                    if (sag[j] < sag[j + 1]) {
                        temp = sag[j + 1];
                        sag[j + 1] = sag[j];
                        sag[j] = temp;
                    }
                }
            }
            ArrayList saga = new ArrayList();
            for (int i = 0; i < sag.length; i++) {
                saga.add(sag[i]);

            }
            for (int i = 0; i < saga.size(); i++) {

                for (int j = i + 1; j < saga.size(); j++) {
                    if (saga.get(i).equals(saga.get(j))) {
                        saga.remove(j);
                        j--;
                    }
                }

            }


            for (int i = 0; i < saga.size(); i++) {
                for (int j = 0; j < a.size(); j++) {
                    String jl = a.get(j);
                    if (saga.get(i).equals(jl.length()))
                        System.out.println(jl);
                }
            }
            break;
        }
    }


}
}

回答by Ketan Ramteke

Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]

让我们采用以下 String inputArray = ["abc","","aaa","a","zz"] 数组

we can use Comparator for sorting the given string array to sort it based on length with the following code:

我们可以使用 Comparator 对给定的字符串数组进行排序,以使用以下代码根据长度对其进行排序:

String[] sortByLength(String[] inputArray) {
        Arrays.sort(inputArray, new Comparator<String>(){
            public int compare(String s1, String s2){
                return s1.length() - s2.length();
            }
        });
        return inputArray;
    }

回答by AlexPes

For instance, the following:

例如,以下内容:

ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);

By lambda:

通过拉姆达:

str.sort((String s1, String s2) -> s1.length() - s2.length());

By static Collections.sort

通过静态 Collections.sort

 import static java.util.Collections.sort;
    sort(str, new Comparator<String>{
       @Override
         public int compare(String s1, String s2) {
           return s1.lenght() - s2.lenght()
}
});

Both options are implemented by default sortmethod from Listinterface

这两个选项都由List接口的默认排序方法实现

回答by Anuj Singh Somvanshi

import java.util.*;
public class SortStringBasedOnTheirLength {

    public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);

      System.out.println("Enter String:");

      String str=sc.nextLine();

      String[] str1=str.split("\s");

      for(int i=0;i<str1.length;i++)
      {
          for(int j=i+1;j<str1.length;j++)
          {
              if(str1[i].length()>str1[j].length())
              {
                 String temp= str1[i];
                 str1[i]=str1[j];
                 str1[j]=temp;
              }
          }
      }

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

}