1

I am using one vector of strings and the strings are not in lower case. I want them to covert to lower case.

For converting string to lower case, I am using following method.

std::transform(strCmdLower.begin(), strCmdLower.end(), strCmdLower.begin(), ::tolower);

I can iterate vector and convert each string but I would like to know is there any library functions available for this purpose like above. Copying to new vector also fine.

std::vector<std::string> v1;
v1.push_back("ABC");
v1.push_back("DCE");

std::vector<std::string> v2(v1.begin(), v1.end());
Arun
  • 2,247
  • 3
  • 28
  • 51
  • Have a look. https://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case – Aditi Rawat Oct 31 '17 at 10:37
  • With reference to the link proposed by @AditiRawat, note that your use of `::tolower` is **undefined behaviour** for non-ASCII-7 input. Personally I recommend [not using `std::string`](https://stackoverflow.com/a/24063783/60281) if there is any chance of having to handle text beyond ASCII-7. – DevSolar Oct 31 '17 at 10:49
  • You should clarify the _encoding_ used by the strings you store in `std::string`: Are they **pure ASCII** (7-bit) strings? Do you use **UTF-8**? Or some other **code page**? As already written, `tolower` is guaranteed to work only for pure ASCII strings. A valid alternative for **Unicode** is suggested by @DevSolar [in this answer](https://stackoverflow.com/a/24063783/1629821). – Mr.C64 Oct 31 '17 at 12:22
  • My string will have only pure ASCII characters – Arun Oct 31 '17 at 15:00

1 Answers1

2

You can still use std::transform with a lambda, e.g.

std::vector<std::string> v1;
v1.push_back("ABC");
v1.push_back("DCE");

std::vector<std::string> v2;
v2.reserve(v1.size());

std::transform(
    v1.begin(), 
    v1.end(), 
    std::back_inserter(v2), 
    [](const std::string& in) {
        std::string out;
        out.reserve(in.size());
        std::transform(in.begin(), in.end(), std::back_inserter(out), ::tolower);
        return out;
    }
);

LIVE

songyuanyao
  • 169,198
  • 16
  • 310
  • 405