Case-specific sorting of strings


Strings are the storage elements for storing different kinds of letters and symbols. It is indicative of a stream of characters in C++. Strings are denoted in double quotes or single quotes.

The given input string can be comprised of both uppercase and lowercase characters. The problem statement is to change the case of the characters of the string, in such a way that the letter which was originally written in lowercase is converted into uppercase and vice versa. Some of the examples illustrating the problem statement are as follows −

Sample Examples

Example 1 : "AbCd"

Output : bAdC

The case of the characters is swapped in the output string.

The problem statement can be solved using two different methods, which are,

  • Using STL

  • Using count array

Method 1: Using C++ STL

Using C++ STL, the upper lower case characters are processed and stored in different vectors. These vectors are then used to access the string and then modify the character case, by picking the required letter from the appropriate vector. The following method is used in this approach

Syntax

push_back()

This method is used to insert an element into the called vector. This increases the size of the vector. The element is inserted at the end of the vector.

vector.push_back(val)

Parameters

vector - The vector in which the value is to be pushed

val - The value to be inserted in the vector

Algorithm

  • Step 1 − Two vectors, upper and lower are initialised to store the upper and lower case characters respectively.

  • Step 2 − The vectors upper and lower are both sorted.

  • Step 3 − The input string, str is traversed and the following two possibilities may arise

    • In case a lower case character is encountered, a character from the upper vector is fetched using the pointer cnt1, and the pointer value is then incremented.

    • In case an upper case character is encountered, a character from the lower vector is fetched using the pointer cnt2, and the pointer value of this vector is then incremented.

  • Step 4 − The final output string is then returned.

Example

//including the required libraries
#include <bits/stdc++.h>
using namespace std;

// Function to return the sorted string
void casesorting(string str){
   int len = str.length();
   
   //vectors to store upper and lower case characters respectively
   vector<char> upper;
   vector<char> lower;
   
   //traversing the string
   for (int i = 0; i < len; i++) {
      char ch = str[i];
      
      //if upper case character
      if (ch >= 'A' && ch <= 'Z')
      
      //store in upper vector
      upper.push_back(str[i]);
      
      //if lower case character
      if (ch >= 'a' && ch <= 'z')
      
      //store in lower vector
      lower.push_back(ch);
   }
   
   //performing sorting
   sort(lower.begin(), lower.end());
   sort(upper.begin(), upper.end());
  
   //declaring two counters for two vectors
   int cnt1 = 0, cnt2 = 0;
   for (int i = 0; i < len; i++) {
      char ch = str[i];
      
      //if lower case
      if (ch >= 'a' && ch <= 'z') {
        
         //pick character from upper vector
         str[i] = upper[cnt1];
         cnt1++;
      }
      
      // Else pick the uppercase character
      else if (ch >= 'A' && ch <= 'Z') {
         str[i] = lower[cnt2];
         cnt2++;
      }
   }
   
   //print the string
   cout << "\nCase specific sorting of string : "<<str;
}
int main(){
  
   //input string
   string str = "lEaRNAtTutoRIaLPoIntS";
   cout<<"Entered String:"<<str;
  
   //calling the method
   casesorting(str);
   return 0;
}

Output

Entered String:lEaRNAtTutoRIaLPoIntS
Case specific sorting of string : AaEalnIoILNotPttRuRS

Method 2: Using count array

This approach uses two arrays, lower and upper of the capacity to store 23 characters. The lower case count of each character is stored in the lower array and the upper case character count is stored in the upper array respectively.

Algorithm

  • Step 1 − Two arrays, upper and lower are initialised to store the counts of the upper and lower case characters respectively.

  • Step 2 − The input string, str is traversed and the following two possibilities may arise −

    • In case a lower case character is encountered, a character with the count>0 from the upper array is fetched using the pointer cnt1

    • The count of this particular character is decremented. In case the count becomes zero, the counter value cnt1 is incremented.

    • In case an upper case character is encountered, a character with the count>0 from the lower array is fetched using the pointer cnt2.

    • The count of this particular character is decremented. In case the count becomes zero, the counter value cnt2 is incremented.

  • Step 3 − The final output string is then returned.

Example

//including the required libraries
#include <bits/stdc++.h>
using namespace std;

// Function to return the sorted string
void casesorting(string str){
   int len = str.length();
   int numchar = 26;
  
   //store lower and upper case character count
   //initialising the arrays with 0
   int lower[numchar]={0};
   int upper[numchar]={0};
   
   //traversing the string
   for(int i = 0; i < len;i++){
   
      //accessing the character
      char ch = str[i];
      
      //if upper case character
      if(ch>='A' && ch<='Z')
         upper[ch-'A']++;
      else
      
         //if lower case character
         lower[ch-'a']++;
   }
   
   //output string
   string ostr= "";
   
   //initialising the counters for upper and lower array
   int cnt1=0;
   int cnt2=0;
   for(int i = 0; i < len ;i++){
      char ch = str[i];
      
      //check if lower case character
      if(ch>='a' && ch<='z'){
        
         //check if count of current char is more than 0
         if(lower[cnt1]>0){
            char temp = (char)('a'+cnt1);
            ostr+=temp;
         
            //decrement count of current char
            lower[cnt1]--;
         } else {
            
            //if current count of character is 0
            while(cnt1<26 && lower[cnt1]==0){
               cnt1++;
            }
           
            //appending character to string
            char temp = (char)('a'+cnt1);
            ostr+=temp;
           
            //decrement count of current char
            lower[cnt1]--;
         }
      } else {
         if(upper[cnt2]>0){
            ostr+=(char)('A'+cnt2);
            upper[cnt2]--;
         } else {
            while(cnt2<26 && upper[cnt2]==0){
               cnt2++;
            }
            char temp = (char)('A'+cnt2);
            ostr+=temp;
            upper[cnt2]--;
         }
      }
   }
  
   //print the string
   cout << "\nCase specific sorting of string : "<<ostr;
}
int main(){
   
   //input string
   string str = "HeYa";
   cout<<"Entered String:"<<str;
   
   //calling the method
   casesorting(str);
   return 0;
}

Output

Entered String:HeYa
Case specific sorting of string : HaYe

Conclusion

Case conversion is an important aspect of the strings in C++. Case specific sorting is simply used to provide an inversion for the original case of the characters. The best approach is to used an O(n) time complexity solution, which requires the maintenance of just two arrays and solving the problem using the count array.

Updated on: 15-Mar-2023

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements