Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Sort a String in Java alphabetically in Java?
Sorting a string alphabetically means rearranging its characters in order, from A to Z. For example, the string "java" becomes "aajv" after sorting.
Different ways to sort a String Alphabetically
There are two ways to do this in Java using different approaches -
-
Using toCharArray() and Arrays.sort() Method
-
Sorting the array manually
Using toCharArray() and Arrays.sort() Method
The toCharArray() method of this class converts the String to a character array and returns it. To sort a string value alphabetically -
-
Get the required string.
-
Convert the given string to a character array using the toCharArray() method.
-
Sort the obtained array using the sort() method of the Arrays class.
-
Convert the sorted array to a String by passing it to the constructor of the String array.
Example
Following is an example to sort a string alphabetically -
import java.util.Arrays;
import java.util.Scanner;
public class SortingString {
public static void main(String args[]) {
String str = "Hello welcome to Tutorialspoint";
char charArray[] = str.toCharArray();
Arrays.sort(charArray);
System.out.println(new String(charArray));
}
}
Let us compile and run the above program, which will give the following result -
Hello welcome to Tutorialspoint
Sorting the array manually
The following are the steps to sort the array manually -
-
Get the required string.
-
Convert the given string to a character array using the toCharArray() method.
-
Compare the first two elements of the array.
-
If the first element is greater than the second, swap them.
-
Then, compare the 2nd and 3rd elements if the second element is greater than the 3rd, swap them.
-
Repeat this till the end of the array.
Example
Following is an example -
import java.util.Arrays;
import java.util.Scanner;
public class SortingString {
public static void main(String args[]) {
int temp, size;
String str = "Tutorialspoint";
char charArray[] = str.toCharArray();
size = charArray.length;
for(int i = 0; i < size; i++ ) {
for(int j = i+1; j < size; j++) {
if(charArray[i]>charArray[j]) {
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = (char) temp;
}
}
}
System.out.println("Third largest element is: "+Arrays.toString(charArray));
}
}
Let us compile and run the above program, which will give the following result -
Tutorialspoint Third largest element is: [T, a, i, i, l, n, o, o, p, r, s, t, t, u]