First of all we convert the string into lower case. Now as we know, String is not a mutable, we convert the string into a StringBuffer Object. Now easily use the selection sort method on the StringBuffer object. Here we use a method setCharAt(), which is in the StringBuffer class but not in String Class.
import java.util.*; public class AlphaSort { public static void main(String []args) { Scanner sc=new Scanner(System.in); System.out.print("Enter A String : "); String str=sc.nextLine(); str=str.toLowerCase(); StringBuffer sb=new StringBuffer(str); char c; for(int i=0;i<sb.length();i++) { for(int j=0;j<sb.length();j++) { if(sb.charAt(i)<sb.charAt(j)) { c=sb.charAt(i); sb.setCharAt(i,sb.charAt(j)); sb.setCharAt(j,c); } } } System.out.println(sb.toString().trim()); } }
Enter A String : national Public school
aabcchiillnnooopstul