Java Tutorial
This java program is used to sort the characters in string as alphabetical order using StringBuffer class.
charAt method is used to get the character at the provided index in the string.
setCharAt method is used to set the provided character at the provided index in the string.
Gets the string as user input and sorting the characters in string and prints the sorted characters as string.
import java.util.Scanner; public class StringCharactersSorting { // Sorting string characters public static String stringCharsSorting(String str){ StringBuffer strBuffer = new StringBuffer(str); int numberOfChars = strBuffer.length(); for(int i=0;i<numberOfChars-1;i++){ for(int j=i+1;j<numberOfChars;j++){ if(strBuffer.charAt(i) > strBuffer.charAt(j)){ char temp = strBuffer.charAt(i); strBuffer.setCharAt(i, strBuffer.charAt(j)); strBuffer.setCharAt(j, temp); } } } return strBuffer.toString(); } public static void main(String[] args){ String str; Scanner in = new Scanner(System.in); System.out.println("String Characters Sorting"); System.out.println("-------------------------"); System.out.print("Enter string: "); str=in.next(); in.close(); str = stringCharsSorting(str); System.out.println("Sorted characters in String: "+str); } }Output:
D:\Java_Programs>javac StringCharactersSorting.java D:\Java_Programs>java StringCharactersSorting String Characters Sorting ------------------------- Enter string: codingpointer.com Sorted characters in String: .ccdegiimnnoooprt
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page