mercredi 27 septembre 2017

How to get the string to be run through the loop a second time with the adjusted string index?

Trying to write code that will take an input string and "abbreviate" it. for example if aabb is given then the output should be bc. Basically if there's any double letters it goes up to the next letter in the alphabet so aa = b and so on. This works fine for the first run through but it won't loop through until completion. if the given string is aaaa the output should be c but instead the code outputs bb. how can I adjust my code to run the string an appropriate amount of times?

string abbreviate (string loc){

int loopCount;
sort(loc.begin(), loc.end());

for ( unsigned int i = 0; i < loc.length() ; i++){


    if(loc[i] == loc[i+1]) {
        if(loc[i] == 'a'){
            loc[i] = 'b';
            loc[i+1] = 0;

        }else if(loc[i] == 'b'){
            loc[i] ='c';
            loc[i+1]= 0;
        }else if(loc[i] == 'c'){
            loc[i] ='d';
            loc[i+1]= 0;
        }else if(loc[i] == 'd'){
            loc[i] = 'e';
            loc[i+1]= 0;
        }else if(loc[i] == 'e'){
            loc[i] ='f';
            loc[i+1]= 0;
        }else if(loc[i] == 'f'){
            loc[i] ='g';
            loc[i+1]= 0;
        }else if(loc[i] == 'g'){
            loc[i] ='h';
            loc[i+1]= 0;
        }else if(loc[i] == 'h'){
            loc[i] ='i';
            loc[i+1]= 0;
        }else if(loc[i] == 'i'){
            loc[i] ='j';
            loc[i+1]= 0;
        }else if(loc[i] == 'j'){
            loc[i] ='k';
            loc[i+1]= 0;
        }else if(loc[i] == 'k'){
            loc[i] ='l';
            loc[i+1]= 0;
        }else if(loc[i] == 'l'){
            loc[i] ='m';
            loc[i+1]= 0;
        }else if(loc[i] == 'm'){
            loc[i] ='n';
            loc[i+1]= 0;
        }else if(loc[i] == 'n'){
            loc[i] ='o';
            loc[i+1]= 0;
        }else if(loc[i] == 'o'){
            loc[i] ='p';
            loc[i+1]= 0;
        }else if(loc[i] == 'p'){
            loc[i] ='q';
            loc[i+1]= 0;
        }else if(loc[i] == 'q'){
            loc[i] ='r';
            loc[i+1]= 0;
        }else if(loc[i] == 'r'){
            loc[i] ='s';
            loc[i+1]= 0;
        }else if(loc[i] == 's'){
            loc[i] ='t';
            loc[i+1]= 0;
        }else if(loc[i] == 't'){
            loc[i] ='u';
            loc[i+1]= 0;
        }else if(loc[i] == 'u'){
            loc[i] ='v';
            loc[i+1]= 0;
        }else if(loc[i] == 'w'){
            loc[i] ='x';
            loc[i+1]= 0;
        }else if(loc[i] == 'x'){
            loc[i] ='y';
            loc[i+1]= 0;
        }else if(loc[i] == 'y'){
            loc[i] ='z';
            loc[i+1]= 0;
        }


    }
}

return loc;
}

Aucun commentaire:

Enregistrer un commentaire