String sorting problem

 

Title Description: write a program to sort the characters in the input string according to the following rules.

Rule 1: English letters are arranged from A to Z, not case sensitive.

For example, input: Type output: epTy

Rule 2: when the case of the same English letter exists at the same time, it is arranged in the order of input.

For example, input: BabA output: aABb

Rule 3: keep other characters that are not English letters in their original positions.

For example, input: By?e output: Be?y

Input: A Famous Saying: Much Ado About Nothing(2012/8) output: a aaaabc dfgghh: iimm nnooos stuuuy (2012 / 8)

#include<iostream>
#include<string>
using namespace std;

int main(){
    int len,count=0;
    string line;
    while(cin >> line){  //Possible spaces in input characters, consider multiple inputs
    len = line.size();
    
    for(int i = 0; i<len; i++){  //Determine the number of characters in the string
        if((line[i]>='a'&&line[i]<='z')||(line[i]>='A'&&line[i]<='Z')){
            count++;
        }
    }
    string str(count,'0'); //Initializing a word store object
    int k=0;
    for(int i = 0; i<len; i++){ //Copy the extracted letters to the storage object
        if((line[i]>='a'&&line[i]<='z')||(line[i]>='A'&&line[i]<='Z')){
            str[k]=line[i];
            k++;
        }
    }
        
    k=0;
    string temp(count,'0'); //Initialize sort storage array
    for(int i = 0; i<26; i++){  //Sort the extracted letters, and compare the letters in the order position one by one according to the difference with the first letter
       for(int j = 0; j<count; j++){
           if(str[j]-'a'==i||str[j]-'A'==i){
                 temp[k] = str[j];
                 k++;
           }
        }
     }
    k=0;
    for(int i=0;i<len;++i){ //Rewrite sorted letters to extraction location
        if((line[i]>='a'&&line[i]<='z')||(line[i]>='A'&&line[i]<='Z')){
            line[i]=temp[k];
            k++;
        }
    }
    cout << line;
  }
    cout << endl;
    return 0;
}

Compilation and debugging results:

Posted by mdub2112 on Fri, 03 Jan 2020 21:08:25 -0800