×

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java.

Introduction

Firstly, let us revise what is string

Strings are collections of characters that are frequently used in Java programming. Objects in the programming language Java include strings. For creating and manipulating strings, the Java platform offers the String class.

Although there is no method in the string class that explicitly sorts a string, we may nevertheless sort a string by using other techniques one after the other. A series of characters make up the string. String objects in Java are immutable, which simply means they can never be modified after they have been created.

There are two ways to create a string in java

  • By String Literal
  • By new Keyword

By String Literal

The syntax would be as follows

String s = “ Hello Man”;

By new Keyword

String s = new String(“Hello Man”);

Methods for sorting the string

In Java, there are two methods available for sorting any string.

  • Without sort() method
  • With sort() method

Without sort() method

Here, we'll lay out a method for sorting a string without of any specified reasoning. So, from the perspective of an interview, it does become a crucial strategy.

Process

  • By using toCharArray() method of a String class, convert a string to an array.
  • Now check for swapping array elements using nested loops.
  • Print the components of this character array.

Now let us write a simple java code that depicts the above procedure

File name: WithoutSort.java

// Java code that uses the toCharArray() function to alphabetically sort a string without //leveraging the sort() method


// importing the necessary classes
import java.io.*;
import java.util.Arrays;


class WithoutSort {
public static void main(String[] args) throws Exception
{
// separate string input
String str = "helloman";

// string to array conversion for computation
char arr[] = str.toCharArray();


// Nested loops enabling character comparison in the previous character array

char temp;


int i = 0;
while (i < arr.length) {
int j = i + 1;
while (j < arr.length) {
if (arr[j] < arr[i]) {

// evaluating each character individually
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j += 1;
}
i += 1;
}
// Now that the loop is finished, the entire array has been iterated.
System.out.println(arr);
}
}

Output

aehllmno

With sort() method

Process

  • The key logic is to use the String class' toCharArray() function on the input sequence to turn it into a character array.
  • To sort a character array, use the Arrays.sort(char c[]) method.
  • Create an arranged string from the char array using the constructor of the String class.

Now let us write a code for the above process

File name: WithSort.java

// Java code that uses the toCharArray() function to alphabetically sort a string The sort() //technique is employed here.
// Arrays class from the java.util package being imported
import java.util.Arrays;
public class WithSort {
// To sort a string alphabetically
public static String sortString(String inputString)
{
// raw string to character array conversion
char tempArray[] = inputString.toCharArray();
// utilizing temp array to sort
Arrays.sort(tempArray);
// providing a new, sorted string
return new String(tempArray);
}
public static void main(String[] args)
{
// individual string entered
String inputString = "helloman";
String outputString = sortString(inputString);
// Printing and displaying instructions
// Enter a string
System.out.println("Input String : " + inputString);
// Resulting string
System.out.println("Output String : "+ outputString);
}
}

Output

aehllmno

There is another procedure that is considered to be improved technique by using the sort() method only

Procedure

  • Raw string into character array conversion There isn't a simple way to do it. To populate the array, we'll use a for loop.
  • To sort a character array, use the Arrays.sort(T [], Comparator c) method. To achieve this, we must create the compare() methodology based on our unique sorting characteristics.
  • The Character array can now be converted to a String using StringBuilder.

The example program would be as follows

File name: WithSort1.java

// Sorting a Mixed String of Capital letters and Lower case letter Characters in Java
// importing the necessary classes
import java.util.Arrays;
import java.util.Comparator;


class WithSort1 {

public static String sortString(String inputString)
{
// converting a string input into a character array
Character tempArray[]
= new Character[inputString.length()];


for (int i = 0; i < inputString.length(); i++) {
tempArray[i] = inputString.charAt(i);
}


// Sort without considering the case
Arrays.sort(tempArray, new Comparator<Character>() {

// comparison of characters
public int compare(Character c1, Character c2)
{
return Character.compare(
Character.toLowerCase(c1),
Character.toLowerCase(c2));
}
});


// To transform a Character array to a String, use StringBuilder.
StringBuilder sb
= new StringBuilder(tempArray.length);


for (Character c : tempArray)
sb.append(c.charValue());


return sb.toString();
}



public static void main(String[] args)
{
// each input string
String inputString = "helloman";


// Sorting the input string and putting it in a string by calling method 1
String outputString = sortString(inputString);
// Input as well as output strings should be printed and displayed.
System.out.println("Input String : " + inputString);
System.out.println("Output String : "
+ outputString);
}
}

Output

aehllmno

Related Topics

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.