Advertisement Jump to content
Sign in to follow this  

converting to upper case

This topic is 4920 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I know this is extremely simple question. But what is the best way to convert a string to all uppercase(or lower for that matter) in c++, while keeping the code as portable as possible. My current solution only works for ascii. I have another one, but I don't know how the performance will be on it(switch on the letter and have case statements for each lowercase letter and change them to uppercase.) Like I said, probably extremely simple, but I haven't found out how. I'm coming from Java where strings have a toUpper method. The reason I want to do this is to work with substrings in the string and I thought it would be better to bring the string onto a format i like. Ok, I'll quit ranting and wait.

Share this post

Link to post
Share on other sites
You can use ASCII key codes instead of a big case statement. Capital letters are ASCII codes 65 to 90 and lower case are 97 to 122. Just check if a character is in the range and then subtract or add 32 to the key code, depending on if you want to convert to upper case or lower case

Edit: Here's an example

char A = 'A';

//Convert A to lowercase
A += 32;

And just create a function and loop through a string like that

Share this post

Link to post
Share on other sites
If you want to upper case a string that may be locale dependent then you'll need to use C++ locales. ex:

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

int main(int, char **) {
locale loc1 ( "German_Germany" ); // or however your compiler specifies locales

char str[] = "Hello, my name is John!";

use_facet<ctype<char> > ( loc1 ).toupper
( &str[0], &string[sizeof(str)] );
cout << "The uppercase string is: " << str << endl;

If you want to stick with normal ASCII string you can use the std::toupper() function in header cctype

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!