fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <cstring>
  4. #include <string>
  5. using namespace std;
  6.  
  7. std::unique_ptr<char[]> ToLower2(const char * const source)
  8. {
  9. int length = strlen(source) + 1;
  10. char * dest = new char[length + 1];
  11. for (int index = 0; index < length; ++index)
  12. {
  13. if (source[index] == ' ')
  14. dest[index] = ' ';
  15. else
  16. dest[index] = tolower(source[index]);
  17. }
  18. return std::unique_ptr<char[]>(dest);
  19. }
  20.  
  21.  
  22. char * ToLower(const char * const source) // should use const really if you don't intend to change it
  23. {
  24. int length = strlen(source) + 1;
  25. char * dest = new char[length + 1];
  26.  
  27. for (int index = 0; index < length; ++index)
  28. {
  29. if (source[index] == ' ')
  30. dest[index] = ' ';
  31. else
  32. dest[index] = tolower(source[index]);
  33. }
  34. return dest;
  35.  
  36. }
  37.  
  38.  
  39. int main() {
  40. std::string s = "BLA BLA";
  41. {
  42. char * lower = ToLower(s.c_str());
  43. cout<<lower<<endl; // use lower
  44. //use some more....
  45. //finished
  46. delete [] lower;
  47. }
  48.  
  49. {
  50. unique_ptr<char[]> lower = ToLower2(s.c_str());
  51. cout<<lower.get()<<endl; // use lower
  52. //use some more....
  53. //finished, lower will "delete itself"
  54. }
  55. return 0;
  56. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
bla bla
bla bla