Cpp string to lower

C++ tolower()

The tolower() function in C++ converts a given character to lowercase. It is defined in the cctype header file.

Example

#include #include using namespace std; int main() < 
// convert 'A' to lowercase char ch = tolower('A');
cout // Output: a

tolower() Syntax

The syntax of the tolower() function is:

tolower() Parameters

The tolower() function accepts the following parameter:

tolower() Return Value

The tolower() function returns:

  • For Alphabets — the ASCII code of the lowercase version of ch
  • For Non-Alphabets — the ASCII code of ch

tolower() Prototype

The function prototype of tolower() as defined in the cctype header file is:

As we can see, the character argument ch is converted to int i.e. its ASCII code.

Since the return type is also int , tolower() returns the ASCII code of the converted character.

tolower() Undefined Behavior

The behaviour of tolower() is undefined if:

  • the value of ch is not representable as unsigned char , or
  • the value of ch is not equal to EOF .

Example 1: C++ tolower()

#include #include using namespace std; int main() < char c1 = 'A', c2 = 'b', c3 = '9'; 
cout return 0; >

Here, we have converted the characters c1 , c2 , and c3 to lowercase using tolower() .

Notice the code for printing the output:

Here, we have converted the return value of tolower(c1) to char using the code (char) tolower(c1) .

Also notice that initially:

  • c2 = ‘b’ and so tolower() returns the same value
  • c3 = ‘9’ and so tolower() returns the same value

Example 2: C++ tolower() without Type Conversion

#include #include using namespace std; int main() < char c1 = 'A', c2 = 'b', c3 = '9'; 
cout return 0; >

Here, we have converted the characters c1 , c2 , and c3 to lowercase using tolower() .

However, we have not converted the returned values of tolower() to char . So, this program prints the ASCII values of the converted characters, which are:

Example 3: C++ tolower() with String

#include #include #include using namespace std; int main() < char str[] = "John is from USA."; char ch; cout // convert str[i] to lowercase ch = tolower(str[i]);
cout return 0; >
The lowercase version of "John is from USA." is john is from usa.

Here, we have created a C-string str with the value «John is from USA.» .

Then, we converted all the characters of str to lowercase using a for loop. The loop runs from i = 0 to i = strlen(str) — 1 .

In other words, the loop iterates through the whole string since strlen() gives the length of str .

In each iteration of the loop, we convert the string element str[i] (a single character of the string) to lowercase and store it in the char variable ch .

We then print ch inside the loop. By the end of the loop, the entire string has been printed in lowercase.

Источник

How to convert a string to Uppercase or Lowercase in C++

Given a string, you need to change the case of the string. If the question demands the conversion into uppercase, then change the case to uppercase, else convert the string into lowercase.

Solution

Approach 1 – Using the iteration

In this approach, we will iterate the string and check the case of each character. If the string has to be in all uppercase, we will change the lowercase characters to their uppercase equivalent. Else, if we want a lowercased string, then we will convert all the uppercase characters to their lowercase equivalent.

For Conversion to Lowercase
  • Step 1: Iterate the string.
  • Step 2: For each character, check if it is uppercase or not. If the character is in uppercase:
    • Calculate the difference between the ASCII value of character and capital A. For example: If the character is B , the difference is B-A = 1.
    • Next, convert the uppercase character to lowercase by adding the difference of ASCIIs to small a and then typecasting it to the character.
    str[i]=((char)(str[i]-'A'+'a')) // Changing uppercased character to lowercase
    • Typecasting is necessary because on the addition of a numerical value(the difference of ASCIIs) to a character( ‘a’ ) returns a numerical value, which further has to be converted to a character. For example, if we add 1 to a (ASCII=97) then it will return 98. This is why it is necessary to typecast after the summation.
    • Step 3: If the character is not uppercase, pass.
    Implementation of Approach 1 – Conversion to lowercase

    #include int main() < std::string str="tHe CoDiNg bOt"; // Sample string for(int i=0;i=’A’ && str[i] <='Z')< // If the character is Uppercase str[i]=((char)(str[i]-'A'+'a')); // Conversion from uppercase to lowercase, update character value >> std::cout

    For Conversion to Uppercase
    • Step 1: Iterate the string.
    • Step 2: For each character, check if it is lowercase or not. If the character is lowercase:
      • Calculate the difference between the ASCII value of character and small a . For example: If the character is b , the difference is b-a = 1 .
      • Next, convert the lowercase character to uppercase by adding the difference of ASCIIs to capital A and then typecasting it to the character.
      str[i]=((char)(str[i]-'a'+'A')); // Converting from smallercase to the Uppercase, update the character value
      • Typecasting is necessary because on the addition of a numerical value(the difference of ASCII) to a character returns a numerical value, which further has to be converted to a character. For example, if we add 1 to A(ASCII=65), then it will return 66. This is why it is necessary to typecast after the summation.
      • Step 3: If the character is not lowercase, then leave it as it is.
      Implementation of Approach 1 – Conversion to Uppercase
      #include int main() < std::string str="tHe CoDiNg bOt"; // Sample string for(int i=0;i='a' && str[i] <='z')< // If the character is lowercase, then convert it into uppercase character str[i]=((char)(str[i]-'a'+'A')); >> std::cout

      Note: Time and Space complexity is the same for both type of conversions – Uppercase to Lowercase and Lowercase to Uppercase.

      • Time Complexity: O(N) – Iterating over the string is a linear-time operation, hence O(N) time complexity.
      • Space Complexity: O(1) – Since we are updating the already existing string, there’s no additional auxiliary space involved. Hence space complexity is O(1) .

      Approach 2 – Using the built-in STL function

      This approach uses std::transform function from C++ STL. It comes under the header .

      Transform applies a certain operation to all the elements of the container and returns the modified container. We will use ::tolower function along with transform function to convert all the characters to lowercase.

      Implementation of Approach 2

      #include // IO #include // std::transform int main() < std::string str="tHe CoDiNg bOt"; // Sample string std::transform(str.begin(),str.end(),str.begin(). tolower); // Using transform function, converting the string to all lowercase in place. std::cout

      Bonus

      We can use string::at along with std::tolower to access and modify the value at a particular position in a string. std::tolower converts uppercase characters to lowercase.

      #include #include int main() < std::string str="The coding bot"; // First letter uppercase str.at(0) = std::tolower(str.at(0)); // Lowercase the first character of the string,rest all characters are already lowercase std::cout*/ return 0; >

      That’s all, folks .

      Источник

      Raymii.org

      I’m using codewars to practice my development skills. Today I learned a method to transform a std::string’s casing, either to uppercase or lowercase. It uses a lambda and does loop over all characters in the string. Researching it further, I also found out how to do unicode strings with Boost. This article also includes a mini howto on installing Boost on Windows 10 via mingw for use with CLion.

      Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:

      Case transformation for ascii

      The codewars assignment was to count unique lowercase characters in a string, then return the character which was found the most. For the string «hello» this would be l since it’s found twice. To do this I first needed to convert the string to lowercase. This is the code I used to lowercase the string for the codewars practice:

      #C:\Users\Remy\CLionProjects\test1\cmake-build-debug\src\example.exe uppercase 
      #C:\Users\Remy\CLionProjects\test1\cmake-build-debug\src\example.exe LOWERCASE 

      Non-ASCII

      Remember: everytime you assume text is ASCII, a kitten dies somewhere.

      The code above does not work with Emoji’s:

      std::string inStr = "\U0001F4A9 "; std::transform(inStr.begin(), inStr.end(), inStr.begin(), [](unsigned char c)< return std::tolower(c); >); std::cout  

      This won't give the expected result. I'm using an image since your browser will probably not render this correctly:

      img

      A unicode string like a common german word will also not work, same kind of weird output.

      But, with Boost and ICU you can get this to work. The setup is difficult, but when you have it compiling and working, it's a pleasure to work with. You can just pass entire strings instead of looping over every character.

      Boost

      Boost is a set of libraries for C++ development, of which most end up in the standard library after a few years.

      To include Boost in your cmake project, either install it with your package manager or download it manually.

      Installing Boost on Windows 10 or Ubuntu

      On Ubuntu 18.04 it's as simple as:

      apt-get install libboost-dev-all 

      TL;DR: On Windows 10 use this mingw build or be warned. Here be dragons.

      It cost me multiple hours of troubleshooting and debugging. Appearantly mingw and Boost on Windows are not the best of friends. Especially not if you also need Locale , then libICU is required as well. If you use Visual Studio and MSVC or CLion with MSVC instead of Mingw it all should be less problematic. libICU provides downloads for MSVC , for MinGW you're on your own, good luck with compiling.

      Open a cmd, navigate to the folder and build Boost. If you have visual studio installed you can use that, I use mingw so I have to specify that and I have to run a mingw cmd prompt (via the .bat file provided by mingw). Make sure to have g++ available as command:

      C:\Users\Remy\Downloads\boost_1_71_0\boost_1_71_0>g++ --version g++ (i686-posix-sjlj, built by strawberryperl.com project) 4.9.2 Copyright (C) 2014 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
      C:\Users\Remy\Downloads\boost_1_71_0\boost_1_71_0>bootstrap.bat gcc Building Boost.Build engine Generating Boost.Build configuration in project-config.jam for msvc. Bootstrapping is done. To build, run: .\b2 [. ] 
      b2 toolset=gcc [lots and lots of compiling later] 1 file(s) copied. . failed updating 666 targets. . skipped 204 targets. . updated 1573 targets. 

      This will install into C:\Boost and the findBoost cmake package will detect it. If you specify a different folder, you need to set BOOST_ROOT as environment variable or pass it to cmake.

      In your CMakeLists.txt file the following options might help with debugging if you get errors:

      set (Boost_DEBUG ON) set (Boost_ARCHITECTURE "-x32") set (Boost_USE_STATIC_LIBS ON) set (Boost_USE_MULTITHREADED ON) set (Boost_DETAILED_FAILURE_MSG ON) 

      Do note that I spent a few hours fiddling and trying to get the boost.Locale library to compile. I ended with a linker error:

      C:/PROGRA~2/MINGW-~1/I686-8~1.0-P/mingw32/bin/../lib/gcc/i686-w64-mingw32/8.1.0/ ../../../../i686-w64-mingw32/lib/../lib/libiconv.a(localcharset.o):localcharset.c :(.text+0x73): undefined reference to `_imp__GetACP@0' 

      Due to not having libicu installed. As stated earlier, I gave up due to ICU as far as I could find only providing MSVC compatible builds, not MinGW builds.

      Continue on with this guide on a Linux system if you want to follow along, or use CLion with MSVC instead of MinGW.

      Update after another few hours of debugging: when using this build of mingw by Stephan T. Lavavej, the code and cmake does compile and link without errors.

      Boost in your CMakeLists file

      If you've followed my setup guide for CMake then you should add this to the main root-folder CMakeLists.txt file right before include_directories :

      find_package(Boost REQUIRED COMPONENTS locale) if(Boost_FOUND) include_directories($) message("-- Boost found: $") else() message(FATAL_ERROR "Boost not found!") endif() 

      In the src/CMakeLists.txt file, add the following at the bottom:

      if(Boost_FOUND) target_link_libraries ($ $) message("-- Boost link to: $") else() message(FATAL_ERROR "Boost not found!") endif() 

      If all went well, your CMake output should include the two new messages:

      -- Boost found: 1.71.0 -- Boost link to: 1.71.0 -- Configuring done -- Generating done -- Build files have been written to: C:/Users/Remy/CLionProjects/test1/cmake-build-debug 

      Boost locale conversion code

      This is the code I used with Boost to convert uppercase to lowercase:

      boost::locale::generator gen; std::locale loc=gen(""); std::locale::global(loc); std::cout.imbue(loc); std::string grussen = "grussEN"; std::string poopla = "\U0001F4A9"; std::cout  

      My static site generator doesn't like the german S and U, it will not render it correctly. Here's a picture of the code:

      boost1

      The result works as you would expect:

      Источник

      Читайте также:  !DOCTYPE
Оцените статью