C++ example

How to convert a string to lowercase in C++

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

std::string has no to_lower member. Run std::tolower over every character with std::transform: std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });. The lambda takes unsigned char on purpose: passing a negative char to std::tolower is undefined behaviour. Swap in std::toupper for uppercase. It changes ASCII letters only.

Lowercasing looks like a one-liner, and in C++ it nearly is, but the obvious one-liner, std::transform(..., std::tolower), does not compile, and the next most obvious one, ::tolower, compiles with a bug waiting in it. The sections below show the safe std::transform form, a plain loop and the char traps behind the unsigned char cast, what happens to UTF-8 text, and then the reason most people lowercase in the first place: comparing, sorting, searching and looking up strings without caring about case. Each example runs on this page: hit Run, then edit the code and run it again.

1std::transform with std::tolowerRecommended

std::transform(first, last, out, f) calls f on every character and writes the result to out; pass s.begin() as out and it rewrites the string in place. std::tolower from <cctype> does one character, so wrap it in a lambda that takes unsigned char. A small to_lower function that takes the string by value gives you a lowercase copy and leaves the original alone. C++20 adds std::ranges::transform, which takes the whole string instead of two iterators.

lower_transform.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

// Take the string by value: the caller's copy stays as it was
std::string to_lower(std::string s) {
    // The lambda takes unsigned char: std::tolower needs a value
    // that fits in unsigned char (or EOF), and plain char may be negative
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c) { return std::tolower(c); });
    return s;
}

std::string to_upper(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c) { return std::toupper(c); });
    return s;
}

int main() {
    std::string name = "Hello, World! C++20";
    std::cout << to_lower(name) << '\n';
    std::cout << to_upper(name) << '\n';
    std::cout << name << '\n';  // unchanged

    // In place: transform writes back into the same string
    std::string cmd = "SELECT * FROM Users";
    std::transform(cmd.begin(), cmd.end(), cmd.begin(),
                   [](unsigned char c) { return std::tolower(c); });
    std::cout << cmd << '\n';

    // C++20: the ranges version takes the whole string
    std::string tag = "MixedCase_ID_42";
    std::ranges::transform(tag, tag.begin(),
                           [](unsigned char c) { return std::tolower(c); });
    std::cout << tag << '\n';
}

Output

to_lower prints hello, world! c++20 and to_upper prints HELLO, WORLD! C++20, while name itself still reads Hello, World! C++20: the by-value parameter was the copy. Digits, spaces and punctuation pass through untouched, as mixedcase_id_42 shows. The lambda returns the int that std::tolower gives back, and writing it into the string converts it back to char. Nothing in the standard library, C++23 included, adds a to_lower member; boost::algorithm::to_lower is the same loop in a library.

2A plain loop, and why the unsigned char cast

A range-for over char& does the same job and reads well to anyone. Two things trip people up here. Passing std::tolower straight to std::transform fails, because std::tolower is an overload set (the <cctype> function plus a two-argument template from <locale>, which GCC's headers pull in), so the compiler cannot pick one: GCC reports no matching function for call to 'transform(... with an <unresolved overloaded function type> and couldn't deduce template parameter '_UnaryOperation'. The popular fix, ::tolower, compiles, but it receives each char as is, and that is the second trap.

lower_loop.cpp
#include <cctype>
#include <iostream>
#include <string>

int main() {
    // A range-for over references changes the string in place
    std::string s = "MAKE ME QUIET";
    for (char& c : s) {
        c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
    }
    std::cout << s << '\n';

    // std::tolower returns an int, so printing it prints a number
    std::cout << std::tolower('A') << '\n';
    std::cout << static_cast<char>(std::tolower('A')) << '\n';

    // A byte above 127 in a plain char is negative here (char is signed),
    // and passing a negative value other than EOF to std::tolower is
    // undefined behaviour. The unsigned char cast makes it 0..255.
    char byte = '\xC9';
    std::cout << "as char: " << static_cast<int>(byte) << '\n';
    std::cout << "as unsigned char: "
              << static_cast<int>(static_cast<unsigned char>(byte)) << '\n';

    // Only letters change; digits, spaces and punctuation pass through
    std::string mixed = "ID-42 [OK]";
    for (char& c : mixed) {
        c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
    }
    std::cout << mixed << '\n';
}

Output

The loop prints make me quiet. std::tolower('A') prints 97, not a, because it returns an int; cast it to char to print a letter. On this compiler char is signed, so the byte 0xC9 is as char: -55, and std::tolower is only defined for EOF and values that fit in unsigned char. Any byte above 127 (every byte of a UTF-8 accented letter) hits that case, which is why the cast to unsigned char, giving as unsigned char: 201, is in every example on this page. Taking unsigned char as the lambda's parameter does the same cast for you.

3Non-ASCII text and UTF-8

std::tolower works on one byte at a time, and in the default "C" locale it changes only A to Z. In UTF-8, É or Σ is two bytes, so a byte-by-byte lowercase leaves it alone. The standard library's next step is wide characters: decode the UTF-8 into a std::wstring with std::mbstowcs, run std::towlower on each character, and encode it back with std::wcstombs. Both conversions follow the C locale, so the program must switch to a UTF-8 locale with std::setlocale first.

lower_utf8.cpp
#include <algorithm>
#include <cctype>
#include <clocale>
#include <cstdlib>
#include <cwctype>
#include <iostream>
#include <string>

// Byte by byte: right for ASCII, blind to anything encoded in several bytes
std::string to_lower_ascii(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c) { return std::tolower(c); });
    return s;
}

// Decode UTF-8 to wide characters, lower each one, encode it again.
// Needs a UTF-8 C locale (set in main); returns the input on bad UTF-8.
std::string to_lower_wide(const std::string& s) {
    std::wstring w(s.size(), L'\0');
    std::size_t n = std::mbstowcs(w.data(), s.c_str(), w.size());
    if (n == static_cast<std::size_t>(-1)) return s;
    w.resize(n);
    for (wchar_t& c : w) c = static_cast<wchar_t>(std::towlower(c));

    std::string out(w.size() * 4, '\0');  // 4 bytes per character at most
    std::size_t m = std::wcstombs(out.data(), w.c_str(), out.size());
    out.resize(m);
    return out;
}

int main() {
    std::string words[] = {"ÉCOLE", "ÜBER", "ΟΔΟΣ", "STRASSE"};

    for (const auto& w : words) {
        std::cout << "tolower:  " << to_lower_ascii(w) << '\n';
    }

    // The program starts in the "C" locale, where towlower knows ASCII only
    if (!std::setlocale(LC_ALL, "C.UTF-8")) {
        std::cout << "no C.UTF-8 locale here\n";
        return 0;
    }
    for (const auto& w : words) {
        std::cout << "towlower: " << to_lower_wide(w) << '\n';
    }
}

Output

Byte by byte, ÉCOLE becomes École and ΟΔΟΣ comes back unchanged. Through towlower the results are école, über and οδοσ. That last one is still wrong: Greek writes a final sigma as ς, so the word is οδος, and one character at a time cannot know which sigma it is. Case rules that depend on context or change the length (German ß uppercases to SS, Turkish I lowercases to a dotless ı) need a Unicode library such as ICU. The C.UTF-8 locale exists on this Linux compiler; locale names differ between systems, so check what setlocale returns, as the example does.

4Comparing and sorting ignoring case

Most lowercasing is really a case-insensitive comparison. Lowering two copies and comparing them with == works, but it allocates two strings per check. std::ranges::equal with a predicate compares the characters in place, and std::ranges::lexicographical_compare with a lowering predicate gives an ordering you can hand to std::ranges::sort. Both take std::string_view, so literals and std::strings both work. The C functions strcasecmp (POSIX) and _stricmp (Windows) do the same job but are not standard C++, so code that uses them is tied to one platform.

compare_icase.cpp
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

// Compare one character pair after lowering both
bool ichar_equal(unsigned char a, unsigned char b) {
    return std::tolower(a) == std::tolower(b);
}

// Equal ignoring case, without building lowered copies.
// ranges::equal checks the lengths too, so "abc" vs "abcd" is false.
bool iequals(std::string_view a, std::string_view b) {
    return std::ranges::equal(a, b, ichar_equal);
}

// Ordering ignoring case: compare the strings character by character
bool iless(std::string_view a, std::string_view b) {
    return std::ranges::lexicographical_compare(
        a, b, [](unsigned char x, unsigned char y) {
            return std::tolower(x) < std::tolower(y);
        });
}

void print(const std::vector<std::string>& v) {
    for (std::size_t i = 0; i < v.size(); ++i) {
        std::cout << (i ? ", " : "") << v[i];
    }
    std::cout << '\n';
}

int main() {
    std::cout << std::boolalpha;
    std::cout << iequals("Hello", "hELLO") << '\n';
    std::cout << iequals("abc", "abcd") << '\n';
    std::cout << ("Hello" == std::string("hello")) << '\n';  // == is exact

    std::cout << iless("apple", "Banana") << '\n';
    std::cout << (std::string("apple") < std::string("Banana")) << '\n';

    // The default sort puts every capital before every lowercase letter
    std::vector<std::string> fruit = {"cherry", "Banana", "apple", "Date"};
    std::ranges::sort(fruit);
    print(fruit);

    std::ranges::sort(fruit, iless);
    print(fruit);
}

Output

iequals("Hello", "hELLO") is true, and iequals("abc", "abcd") is false: the range version of equal compares the lengths too, unlike the three-iterator std::equal, which reads past the end of a shorter second string. Plain < says "apple" is not less than "Banana", because every capital letter sorts before every lowercase one in ASCII, so the default sort gives Banana, Date, apple, cherry. Sorting with iless gives apple, Banana, cherry, Date.

The same less predicate, put in a struct, becomes the comparator of a std::map, and then keys that differ only in case are the same key: what HTTP header names, file names on some systems and SQL keywords need. Adding using is_transparent = void; lets find and contains take a std::string_view or a literal without building a std::string. For "does this text contain that word, ignoring case", std::ranges::search takes the same kind of character predicate.

icase_map.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <map>
#include <string>
#include <string_view>

struct CaseInsensitiveLess {
    // is_transparent lets find() take a string_view without a copy
    using is_transparent = void;
    bool operator()(std::string_view a, std::string_view b) const {
        return std::ranges::lexicographical_compare(
            a, b, [](unsigned char x, unsigned char y) {
                return std::tolower(x) < std::tolower(y);
            });
    }
};

// Substring search ignoring case: std::ranges::search with a predicate
bool icontains(std::string_view text, std::string_view needle) {
    auto hit = std::ranges::search(text, needle, [](unsigned char x, unsigned char y) {
        return std::tolower(x) == std::tolower(y);
    });
    return !hit.empty() || needle.empty();
}

int main() {
    // HTTP header names are case-insensitive, so key the map that way
    std::map<std::string, std::string, CaseInsensitiveLess> headers;
    headers["Content-Type"] = "text/html";
    headers["content-length"] = "512";
    headers["CONTENT-TYPE"] = "application/json";  // same key: overwrites

    std::cout << headers.size() << " headers\n";
    for (const auto& [name, value] : headers) {
        std::cout << name << ": " << value << '\n';  // keeps the first spelling
    }
    std::cout << std::boolalpha;
    std::cout << headers.contains("CONTENT-LENGTH") << '\n';

    std::cout << icontains("Compile and Run C++", "RUN") << '\n';
    std::cout << icontains("Compile and Run C++", "rust") << '\n';
}

Output

Three assignments leave 2 headers: "CONTENT-TYPE" found the existing Content-Type entry and replaced its value, so the map prints Content-Type: application/json, keeping the spelling of the first insert. The lookup contains("CONTENT-LENGTH") is true. icontains finds RUN in Compile and Run C++ and not rust. A std::unordered_map needs a matching hash as well as an equality, both lowering each character. For case-sensitive search and starts_with, see checking if a string contains a substring.

6Which should you use?

MethodHandlesStandardBest for
std::transform + tolower(unsigned char)ASCIIAnyLowercasing a whole string, in place or a copy
std::ranges::transformASCIIC++20The same, without the iterator pair
for (char& c : s) loopASCIIC++11Readable code, extra logic per character
mbstowcs + towlower + wcstombsMost single lettersAny, needs a UTF-8 localeAccented letters without an extra library
ranges::equal / lexicographical_compareASCIIC++20Compare and sort ignoring case, no copies
strcasecmp / _stricmpASCIIPOSIX / WindowsAvoid in portable code
ICUFull UnicodeLibraryReal multilingual text: ß, final sigma, Turkish I

Frequently asked questions

Is there a built-in function to make a std::string lowercase?

No. std::string has no to_lower or to_upper member, not even in C++23. The standard way is std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });, usually wrapped in a small to_lower function. boost::algorithm::to_lower does the same if you already use Boost.

Why does std::transform with std::tolower not compile?

std::tolower names more than one function: the int tolower(int) from <cctype> and a template tolower(charT, const std::locale&) from <locale>. Passed as a bare name, the compiler cannot tell which one you mean and GCC reports <unresolved overloaded function type>. Wrap the call in a lambda instead, which also gives you the place to cast to unsigned char. Writing ::tolower compiles but skips that cast.

How do I convert a single char to lowercase in C++?

Use char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));. The inner cast avoids undefined behaviour for bytes above 127 where char is signed, and the outer one matters because std::tolower returns an int: std::cout << std::tolower('A') prints 97, not a.

How do I compare two strings ignoring case in C++?

Compare character by character with a lowering predicate: std::ranges::equal(a, b, [](unsigned char x, unsigned char y) { return std::tolower(x) == std::tolower(y); }), which also checks that the lengths match. For ordering, use std::ranges::lexicographical_compare with a < predicate. strcasecmp (POSIX) and _stricmp (Windows) work too but are not standard C++.

Why does tolower not change accented letters like É?

std::tolower sees one byte at a time, and in UTF-8 É is two bytes, neither of them an ASCII letter. Converting to std::wstring with std::mbstowcs under a UTF-8 locale and using std::towlower handles most single letters, so ÉCOLE becomes école. Rules that need context or change length, such as the Greek final sigma or German ß, need a Unicode library such as ICU.

Can I make a case-insensitive string type?

Yes: a std::basic_string with a custom char_traits whose eq, lt and compare lower each character makes ==, < and find ignore case. It is a separate type, though, so it does not mix with std::string without conversions. A comparator on the container (std::map<std::string, V, CaseInsensitiveLess>) or a comparison function is usually less work.

Run it yourself

Open any of these in the full C++ editor to tweak, run and share.

C++ playground