pikProgram
pikProgram

Reputation: 43

How do i sort an array of strings by the second char of each string?

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 + " ");

     }
  }

}
}

Upvotes: 2

Views: 6646

Answers (6)

Bahramdun Adil
Bahramdun Adil

Reputation: 6079

You could try this, just add a custom comparator by using Lambda expressions if you are using java version 1.8 or above :

list.add("Bob");
list.add("Dan");
list.add("Kris");
Collections.sort(list, (s1, s2) -> {
    String sb1 = s1.substring(1);
    String sb2 = s2.substring(1);
    return sb1.compareTo(sb2);
    });

System.out.println("list = " + list);

The Result:

list = [Dan, Bob, Kris]

Upvotes: 2

mmuzahid
mmuzahid

Reputation: 2270

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);

output:

Dan
Bob
Kris

Upvotes: 4

Suyash
Suyash

Reputation: 525

Here is sample tested code. You need to use comparator so as to implement the order. Here value of order can be anything based on your requirement. You can replace your current code with this because it is fine for normal sorting as well (based on index 0). It might require some tweaks based on your need.

 String str[] = {"abc","bca","avc","ert"};
    final int ORDER = 1;
    Arrays.sort(str, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
           return o1.toLowerCase().charAt(ORDER) -  o2.toLowerCase().charAt(ORDER) ;
        }
    });

Upvotes: 0

Ray
Ray

Reputation: 637

I haven't tested this one but you could try this one. Replace the condition part of your code by this one. Though, there may be some performance issue.

if (Arr[i].trim().compareTo(Arr[j].trim())>0) {

Replace with:

if (Arr[i].trim().charAt(nthChar) > Arr[j].trim().charAt(nthChar)) {

The nthChar is the character placement to compare.

Upvotes: 0

Amal
Amal

Reputation: 154

Add different implementations of java.util.Comparator based on the requirement and use

public static <T> void sort(List<T> list, Comparator<? super T> c) in collections class to sort the list.

Upvotes: -1

Ken Clubok
Ken Clubok

Reputation: 1238

You want to use a custom comparator.

Upvotes: -2

Related Questions