How to convert std::string to lower case?

后端 未结 26 2237
旧时难觅i
旧时难觅i 2020-11-22 00:01

I want to convert a std::string to lowercase. I am aware of the function tolower(), however in the past I have had issues with this function and it

26条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 00:30

    This is a follow-up to Stefan Mai's response: if you'd like to place the result of the conversion in another string, you need to pre-allocate its storage space prior to calling std::transform. Since STL stores transformed characters at the destination iterator (incrementing it at each iteration of the loop), the destination string will not be automatically resized, and you risk memory stomping.

    #include 
    #include 
    #include 
    
    int main (int argc, char* argv[])
    {
      std::string sourceString = "Abc";
      std::string destinationString;
    
      // Allocate the destination space
      destinationString.resize(sourceString.size());
    
      // Convert the source string to lower case
      // storing the result in destination string
      std::transform(sourceString.begin(),
                     sourceString.end(),
                     destinationString.begin(),
                     ::tolower);
    
      // Output the result of the conversion
      std::cout << sourceString
                << " -> "
                << destinationString
                << std::endl;
    }
    

提交回复
热议问题