How do i convert all alphabets to uppercase using transform ignoring digits?

535 Views Asked by At

I need to convert only letters in the string to uppercase and tried this piece of code which throws an error.

   s = "Dense-123-Sparse-999" 
   std::transform(s.begin(), s.end(), s.begin(), std::toupper);

Expected Output: "DENSE-123-SPARSE-999"

"Error: non-void lambda does not return a value in all control paths [-Werror,-Wreturn-type]"

It's throwing an error since there are digits in the input string. How do I write a lambda function that converts characters to uppercase only if they are an alphabet and not a number?

something like this,

transform_if(s.begin(), s.end(), s.begin, [](char c){ if(isalpha(c)return toupper(c);});

since C++ doesnt have transform_if, i'm looking for a one liner with any other commands.

2

There are 2 best solutions below

2
On

use a Lambda or a function

char upperize(char c)
{
    return toupper(c);
}
transform(s.begin(),s.end(),s.begin(),upperize);
 
transform(s.begin(),s.end(),s.begin(),[](char s){return toupper(s);});
cout<<s;

you can use isalpha also in addition

2
On

Answering my own question, figured out transform and for_each with lambda code. works for letters without accents.

for_each(s.begin(), s.end(), [](char &c) { c = (isalpha(c))? toupper(c):c; } ) ;

or

transform(s.begin(), s.end(), s.begin(), [](char &c) { return (isalpha(c))?toupper(c):c ; });

Thanks to Basile's comments educating us on UTF-8, my code failed for below case:

input: "èéêrię"

output: "èéêRIę" (wrong)

will need to get back and search for UTF-8 library usage