C++ Rearrange a string in sorted order followed by the integer sum


Discuss a problem to rearrange a string of alphabets in sorted order and add all the integers present in the string, for example

Input : str = “adv4fc3”
Output : “ acdfv7”
Explanation: all the letters have been sorted to “acdfv” followed by the sum of integers 4 and 3.

Input: str = “ h2d7e3f ”
Output: “ defh12”
Explanation: all the letters have been sorted to “defh” followed by the sum of integers 2, 7, and 3.

Approach to Find the Solution

We have two tasks to perform in this problem, one is sorting the string, and the other is adding integer values.

  • Sorting the string can be done by keeping the count of every letter in the string and then forming a new string by inserting all the letters according to their count.

  • We can do the addition of integers by adding the integer to a variable every time it comes.

Example

C++ Code for the Above Approach

#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
int main(){
    string str = "h2d7e3f";
        int ch[26] = {0};
    int count = 0;
    // traverse through all the characters of string.
    for (int i = 0; i < str.length(); i++){
        // keeping count of occurance every character.
        if (str[i]>='a' && str[i] <='z')
            ch[str[i] - 97] = ch[str[i] - 97] + 1;
        // If an Integer encounters.
        else
            count = count + (str[i]-'0');
    }
    string final = "";
    // Making a sorted string with the help of ch array.
    for (int i = 0; i < 26; i++){
        char a = (char)('a'+i);
        // insert the current character
        // to new string untill it count ends
        while (ch[i]-- != 0)
            final = final + a;
    }
   //  and finally insert sum of all integers in the string.
    if (count>0)
        final = final + to_string(count);
    cout << "Rearranged string: " << final;
    return 0;
}

Output

Rearranged string: defh12

Explanation of the Above Code

  • Array ch is initialized of size 26 because we need to keep the count of the occurrence of 26 alphabets.

  • In the First loop, we are traversing through the string. For every alphabet, we are incrementing the count of that alphabet. For every integer, we are adding it to the count variable.

  • In the second loop, we are forming a new sorted string from all the counts in which we are appending the character in the string according to their count.

  • And we are finally appending the string with the sum of integers we have counted from the first loop.

Conclusion

In this tutorial, we discussed how to arrange a string in sorted order and solved a problem based on it from the hash table approach. We also discussed the C++ code for this problem. We can write in any other programming language like C, Java, Python, etc. We hope you find this tutorial helpful.

Updated on: 26-Nov-2021

626 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements