Java Program For Case Specific Sorting
Last Updated :
04 Sep, 2021
Given a string S consisting of uppercase and lowercase characters. The task is to sort uppercase and lowercase letters separately such that if the “i”th place in the original string had an Uppercase character then it should not have a lowercase character after being sorted and vice versa. it is described in the illustration as shown below:
Illustration:
Input : srbDKi
Output: birDKs
Processing : After sorting we have to place the lowercase characters to the lowercase and uppercase character to specific uppercase character
Approach:
- We will use two ArrayList one to store the lowercase values and the second to store uppercase values.
- After adding elements into the lists we will sort the list using Collections.sort(list) method
- After sorting, we will traverse the string and check case-specific and store the element at the correct position
Example:
Java
import java.io.*;
import java.util.*;
class GFG {
static String sortString(String str)
{
ArrayList<Character> list = new ArrayList<>();
ArrayList<Character> list2 = new ArrayList<>();
String res = "" ;
for ( int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) >= 'a'
&& str.charAt(i) <= 'z' )
list.add(str.charAt(i));
if (str.charAt(i) >= 'A'
&& str.charAt(i) <= 'Z' )
list2.add(str.charAt(i));
}
Collections.sort(list);
Collections.sort(list2);
int i = 0 ;
int j = 0 ;
for ( int k = 0 ; k < str.length(); k++) {
if (str.charAt(k) >= 'a'
&& str.charAt(k) <= 'z' ) {
res += list.get(i);
++i;
}
else if (str.charAt(k) >= 'A'
&& str.charAt(k) <= 'Z' ) {
res += list2.get(j);
++j;
}
}
return res;
}
public static void main(String[] args)
{
System.out.println(sortString( "defRTSersUXI" ));
}
}
|
Share your thoughts in the comments
Please Login to comment...