Skip to content
Related Articles

Related Articles

Case-specific Sorting of Strings

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 25 Aug, 2022
View Discussion
Improve Article
Save Article

Given string str consisting of uppercase and lowercase characters. The task is to sort uppercase and lowercase characters separately such that if the ith place in the original string had an uppercase character, then it should not have a lowercase character after being sorted and vice versa.

Examples: 

Input: str = “gEeksfOrgEEkS” 
Output: eEfggkEkrEOsS
Explanation: 
uppercase characters order : EEEOS , they are in sorted order and in correct place
lowercase characters order : efggkkrs , they are in sorted order and in correct place

Input: str = “eDefSR” 
Output: eDefRS 

Case-specific Sorting using STL

The idea is to store lower case characters and upper case characters in two different vectors and sort both of the vectors. Then use the sorted vectors to get the sorted string. while traversing the given string

Follow the steps mentioned below to implement the approach:

  • Create two vectors to store the uppercase and lowercase letters seperatly.
  • Sort both the vector.
  • Traverse The string str, and create two int i and j with value 0.
    • If while traversing you found an uppercase letter then change the value with the element present at index i in the uppercase vector
      and increment i by 1
    • If while traversing you found a lowercase letter then change the value with the element present at index j in the lowercase vector
      and increment j by 1
  • Print the string

Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the sorted string
string getSortedString(string s, int n)
{
 
    // Vectors to store the lowercase
    // and uppercase characters
    vector<char> v1, v2;
    for (int i = 0; i < n; i++) {
        if (s[i] >= 'a' && s[i] <= 'z')
            v1.push_back(s[i]);
        if (s[i] >= 'A' && s[i] <= 'Z')
            v2.push_back(s[i]);
    }
 
    // Sort both the vectors
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());
    int i = 0, j = 0;
    for (int k = 0; k < n; k++) {
 
        // If current character is lowercase
        // then pick the lowercase character
        // from the sorted list
        if (s[k] >= 'a' && s[k] <= 'z') {
            s[k] = v1[i];
            ++i;
        }
 
        // Else pick the uppercase character
        else if (s[k] >= 'A' && s[k] <= 'Z') {
            s[k] = v2[j];
            ++j;
        }
    }
 
    // Return the sorted string
    return s;
}
 
// Driver code
int main()
{
    string s = "gEeksfOrgEEkS";
    int n = s.length();
 
    cout << getSortedString(s, n);
 
    return 0;
}

Java




// Java implementation of the approach
import java.util.Collections;
import java.util.Vector;
 
class GFG{
 
// Function to return the sorted string
public static String getSortedString(StringBuilder s,
                                     int n)
{
 
    // Vectors to store the lowercase
    // and uppercase characters
    Vector<Character> v1 = new Vector<>();
    Vector<Character> v2 = new Vector<>();
 
    for(int i = 0; i < n; i++)
    {
        if (s.charAt(i) >= 'a' &&
            s.charAt(i) <= 'z')
            v1.add(s.charAt(i));
 
        if (s.charAt(i) >= 'A' &&
            s.charAt(i) <= 'z')
            v2.add(s.charAt(i));
    }
 
    // Sort both the vectors
    Collections.sort(v1);
    Collections.sort(v2);
 
    int i = 0, j = 0;
 
    for(int k = 0; k < n; k++)
    {
 
        // If current character is lowercase
        // then pick the lowercase character
        // from the sorted list
        if (s.charAt(k) > ='a' &&
            s.charAt(k) <= 'z')
        {
            s.setCharAt(k, v1.elementAt(i));
            ++i;
        }
 
        // Else pick the uppercase character
        else if (s.charAt(k) > ='A' &&
                 s.charAt(k) <= 'Z')
        {
            s.setCharAt(k, v2.elementAt(j));
            ++j;
        }
    }
 
    // Return the sorted string
    return s.toString();
}
 
// Driver code
public static void main(String[] args)
{
    StringBuilder s = new StringBuilder("gEeksfOrgEEkS");
    int n = s.length();
     
    System.out.println(getSortedString(s, n));
}
}
 
// This code is contributed by
// sanjeev2552

Python3




# Python3 implementation of the approach
 
# Function to return the sorted string
def getSortedString(s, n):
 
    # Vectors to store the lowercase
    # and uppercase characters
    v1=[]
    v2=[]
    for i in range(n):
        if (s[i] >= 'a' and s[i] <= 'z'):
            v1.append(s[i])
        if (s[i] >= 'A' and s[i] <= 'Z'):
            v2.append(s[i])
 
    # Sort both the vectors
    v1=sorted(v1)
    v2=sorted(v2)
    i = 0
    j = 0
    for k in range(n):
 
        # If current character is lowercase
        # then pick the lowercase character
        # from the sorted list
        if (s[k] >= 'a' and s[k] <= 'z'):
            s[k] = v1[i]
            i+=1
 
        # Else pick the uppercase character
        elif (s[k] >= 'A' and s[k] <= 'Z'):
            s[k] = v2[j]
            j+=1
 
    # Return the sorted string
    return "".join(s)
 
 
# Driver code
s = "gEeksfOrgEEkS"
ss=[i for i in s]
n = len(ss)
 
print(getSortedString(ss, n))
 
# This code is contributed by mohit kumar 29

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to return the sorted string
    public static String getSortedString(char[] s, 
                                         int n)
    {
 
        // Vectors to store the lowercase
        // and uppercase characters
        List<char> v1 = new List<char>();
        List<char> v2 = new List<char>();
        int i = 0;
        for (i = 0; i < n; i++)
        {
            if (s[i] > 'a' && s[i] <= 'z')
                v1.Add(s[i]);
 
            if (s[i] > 'A' && s[i] <= 'z')
                v2.Add(s[i]);
        }
 
        // Sort both the vectors
        v1.Sort();
        v2.Sort();
        int j = 0;
        i = 0;
        for (int k = 0; k < n; k++)
        {
 
            // If current character is lowercase
            // then pick the lowercase character
            // from the sorted list
            if (s[k] > 'a' && s[k] <= 'z')
            {
                s[k] = v1[i];
                ++i;
            }
 
            // Else pick the uppercase character
            else if (s[k] > 'A' && s[k] <= 'Z')
            {
                s[k] = v2[j];
                ++j;
            }
        }
 
        // Return the sorted string
        return String.Join("", s);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String s = "gEeksfOrgEEkS";
        int n = s.Length;
        Console.WriteLine(getSortedString(s.ToCharArray(), n));
    }
}
 
// This code is contributed by PrinciRaj1992

Javascript




<script>
      // JavaScript implementation of the approach
      // Function to return the sorted string
      function getSortedString(s, n) {
        // Vectors to store the lowercase
        // and uppercase characters
        var v1 = [];
        var v2 = [];
        var i = 0;
        for (i = 0; i < n; i++) {
          if (
            s[i].charCodeAt(0) > "a".charCodeAt(0) &&
            s[i].charCodeAt(0) <= "z".charCodeAt(0)
          )
            v1.push(s[i]);
 
          if (
            s[i].charCodeAt(0) > "A".charCodeAt(0) &&
            s[i].charCodeAt(0) <= "Z".charCodeAt(0)
          )
            v2.push(s[i]);
        }
 
        // Sort both the vectors
        console.log(v1);
        v1.sort();
        v2.sort();
        var j = 0;
        i = 0;
        for (var k = 0; k < n; k++) {
          // If current character is lowercase
          // then pick the lowercase character
          // from the sorted list
          if (
            s[k].charCodeAt(0) > "a".charCodeAt(0) &&
            s[k].charCodeAt(0) <= "z".charCodeAt(0)
          ) {
            s[k] = v1[i];
            ++i;
          }
 
          // Else pick the uppercase character
          else if (
            s[k].charCodeAt(0) > "A".charCodeAt(0) &&
            s[k].charCodeAt(0) <= "Z".charCodeAt(0)
          ) {
            s[k] = v2[j];
            ++j;
          }
        }
 
        // Return the sorted string
        return s.join("");
      }
 
      // Driver code
      var s = "gEeksfOrgEEkS";
      var n = s.length;
      document.write(getSortedString(s.split(""), n));
</script>

Output

eEfggkEkrEOsS

Time Complexity: O(N*log(N))
Auxiliary Space: O(N) 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!