Home > front end >  converting a string to lowercase/uppercase depending upon the count of upper/lower case characters i
converting a string to lowercase/uppercase depending upon the count of upper/lower case characters i

Time:02-10

i have to output a string in all uppercase if count of uppercase characters in it is more otherwise lowercase string will be shown if lowercase characters are more in the string,in case both characters are equal i will print the string in lowercase only this the code i have written , but , it's not giving desired output,like it is returning the same string back to me , please help me with the errors

here's the code,i am using c .

string s;
cin>>s;
int uc=0,lc=0;
for (int i = 0; i < s.size(); i  )
{       
    if(isupper(s[i])){
        uc  ;
    }
    else{
        lc  ;
    }
}
if(uc>lc){
    for (int j = 0; j < s.size(); j  )
    {
        toupper(s[j]);

    }    
    cout<<s<<endl;
}
else{
    for (int k = 0; k < s.size(); k  )
    {
        tolower(s[k]);
    }
    cout<<s<<endl;
}

CodePudding user response:

Your problem is that your are not re-assigning the respective characters of your string resulting in your input string being untouched.

You need to do:

s[j] = toupper(s[j])
s[k] = tolower(s[k]);

Another approach is to convert the string as a whole after your counting procedure - requires to include <algorithm> (credits to this answer):

if (uc > lc) {
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
}
else {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
}

CodePudding user response:

After your first loop, do this:

string result = (uc>lc) ? toupper(s) : tolower(s);
  • Related