如何按每个字符串的第二个字符对字符串数组进行排序? [英] How do i sort an array of strings by the second char of each string?

查看:129
本文介绍了如何按每个字符串的第二个字符对字符串数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序,要求用户将名称输入到数组中,然后按字母顺序对名称进行排序...程序运行良好,但我想知道是否可以对第二,第三位输入的每个名称进行排序,或每个字符串中的第4个字符?例如,如果用户输入了Bob,Dan和Kris,则程序应将其排序为Dan,Bob和Kris.这是我的程序,它按字符串的第一个字母对字符串数组进行排序:

I wrote a program that asks users to input names into an array and then the names are sorted in alphabetical order...The program works good but I was wondering if I could sort each of the names entered by the 2nd, 3rd, or 4th character in each string? For example, if the user entered Bob, Dan, and Kris the program should sort them as Dan, Bob, Kris. This is my program that sorts my array of strings by the first letter of the string:

  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  import java.util.Scanner;


public class SortingAnArrayOfStrings {




public static void main(String[] args) {


{
     //Ask the user for names to add to the array
     List<String> list=new ArrayList<String>();
     Scanner in=new Scanner(System.in);
     do {
         System.out.println(" The names on the list are "+list);
         System.out.println("Would you like to add another name to the list? (y/n)");

         if (in.next().startsWith("y")) {
             System.out.println("Enter:");
             list.add(in.next());
         }else{break;

        }
     } while (true);
    //display the names that have been added to the array
    System.out.println("The names on the list are "+list);

    //sort the array of names in alphabetical order
    String[] Arr=list.toArray(new String[list.size()]);
    String[] stringArray=new String[Arr.length];

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

     //display the sorted list of names
     System.out.println("This is the list of names after sorting them in alphabetical order : ");

     for(String ss:stringArray){
         System.out.print(ss + " ");

     }
  }

}
}

推荐答案

您可以使用自定义的 java.util.Comparator 尝试以下类似方法:

You could try something like bellow using a custom java.util.Comparator:

String[] names = {"Dan", "Bob", "Kris"};
java.util.Collections.sort(java.util.Arrays.asList(names), new java.util.Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // TODO: Argument validation (nullity, length)
        return s1.charAt(1) - s2.charAt(1);//comparision
    }  
});

for (String name : names) System.out.println(name);

输出:

Dan
Bob
Kris

这篇关于如何按每个字符串的第二个字符对字符串数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆