C++ String strcoll() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Locale / i18n

What You’ll Learn

The strcoll() function compares two C-strings using the active locale collation rules—how a language expects text to be ordered in dictionaries, menus, and sorted lists. Unlike strcmp(), which compares raw character codes, strcoll() can respect accents, case conventions, and cultural sorting rules for internationalized programs.

01

Locale Compare

Culture-aware order.

02

Like strcmp

Same return sign.

03

setlocale()

Configure LC_COLLATE.

04

0 / <0 / >0

Equal or order.

05

Sorting Names

User-facing lists.

06

vs strcmp()

Byte vs locale.

Definition and Usage

In C++, strcoll() is declared in <cstring> and uses the collation category of the current C locale (set via setlocale). It is designed for comparing human-readable text where sorting should follow local language rules, not ASCII code points.

The return value follows the same convention as strcmp(): zero for equal, negative if str1 sorts before str2, positive if it sorts after. Results depend on the active locale, so two programs on different systems may order accented names differently unless you set the locale explicitly.

💡
Beginner Tip

Call setlocale(LC_COLLATE, "") near the start of main when you want comparisons to follow the user’s environment. Use strcmp() when you need fast, predictable byte order (identifiers, file paths, protocol tokens).

📝 Syntax

Function signature and locale setup:

C++
#include <cstring>
#include <clocale>

int strcoll(const char* str1, const char* str2);

// Typical setup:
std::setlocale(LC_COLLATE, "");

Parameters

  • str1 — first null-terminated C-string.
  • str2 — second null-terminated C-string.

Return Value

An int less than, equal to, or greater than zero according to locale collation rules. Interpret only the sign unless documented otherwise for your platform.

⚡ Quick Reference

FunctionCompares byBest for
strcmp()Character code unitsIdentifiers, tokens, speed
strcoll()Locale collation rulesUser-visible name lists
strncmp()First n code unitsFixed-width fields
std::string::compareCode units (default)Modern C++ strings
Setup
setlocale(LC_COLLATE, "");

User locale

Compare
strcoll(a, b)

Locale order

Equal?
strcoll(a, b) == 0

Collation match

Sort helper
strcoll(x, y) < 0

x before y

Examples Gallery

Compile with g++ strcoll.cpp -std=c++17 -o strcoll. Output may vary slightly by operating system locale—that is expected for locale-aware functions.

📚 Getting Started

Compare two words with the user’s collation rules.

Example 1 — Basic strcoll() Usage

Set the collation locale, then compare "apple" and "Orange".

C++
#include <iostream>
#include <cstring>
#include <clocale>

int main() {
    std::setlocale(LC_COLLATE, "");

    const char* str1 = "apple";
    const char* str2 = "Orange";

    int result = std::strcoll(str1, str2);

    if (result < 0) {
        std::cout << "str1 sorts before str2.\n";
    } else if (result > 0) {
        std::cout << "str1 sorts after str2.\n";
    } else {
        std::cout << "str1 equals str2 in collation.\n";
    }

    return 0;
}

How It Works

Under many English locales, case-insensitive collation places "apple" before "Orange", unlike raw strcmp where uppercase letters precede lowercase in ASCII order.

Example 2 — strcoll() vs strcmp() Side by Side

See how byte order and locale order can disagree on the same pair of strings.

C++
#include <iostream>
#include <cstring>
#include <clocale>

int main() {
    std::setlocale(LC_COLLATE, "");

    const char* a = "apple";
    const char* b = "Orange";

    int byteCmp = std::strcmp(a, b);
    int localeCmp = std::strcoll(a, b);

    std::cout << "strcmp:  " << (byteCmp < 0 ? "a before b" : "a after b") << "\n";
    std::cout << "strcoll: " << (localeCmp < 0 ? "a before b" : "a after b") << "\n";

    return 0;
}

How It Works

strcmp sees 'a' (97) vs 'O' (79) and reports a after O. Locale collation may ignore case for ordering, reversing the result for user-facing sorts.

📈 Practical Patterns

Sorting, locale setup, and choosing the right compare function.

Example 3 — Sort Names with strcoll()

Use strcoll as the comparison logic when building a sorted name list.

C++
#include <iostream>
#include <cstring>
#include <clocale>
#include <algorithm>

bool localeLess(const char* a, const char* b) {
    return std::strcoll(a, b) < 0;
}

int main() {
    std::setlocale(LC_COLLATE, "");

    const char* names[] = { "Zara", "apple", "Mario", "orange" };
    const int count = 4;

    std::sort(names, names + count, localeLess);

    std::cout << "Sorted names:\n";
    for (int i = 0; i < count; ++i) {
        std::cout << "  " << names[i] << "\n";
    }

    return 0;
}

How It Works

std::sort calls localeLess, which delegates to strcoll. The exact order depends on your OS locale, but it reflects how a dictionary in that language might arrange the names.

Example 4 — Explicit Locale String

You can pass a locale name to setlocale when you need a specific language environment (if installed on the system).

C++
#include <iostream>
#include <cstring>
#include <clocale>

int main() {
    const char* chosen = std::setlocale(LC_COLLATE, "en_US.UTF-8");
    if (chosen == nullptr) {
        std::cout << "Locale not available, using default.\n";
        std::setlocale(LC_COLLATE, "");
    } else {
        std::cout << "Collation locale: " << chosen << "\n";
    }

    const char* s1 = "resume";
    const char* s2 = "résumé";
    std::cout << "strcoll result sign: " << std::strcoll(s1, s2) << "\n";

    return 0;
}

How It Works

Always check whether setlocale succeeded. Accented characters illustrate why locale collation matters—byte comparison and human sorting diverge for international text.

Example 5 — Choose strcmp or strcoll

Pick the compare function based on what you are comparing.

C++
#include <iostream>
#include <cstring>
#include <clocale>

enum class Kind { UserLabel, ProtocolToken };

bool stringsMatch(const char* a, const char* b, Kind kind) {
    if (kind == Kind::UserLabel) {
        return std::strcoll(a, b) == 0;
    }
    return std::strcmp(a, b) == 0;
}

int main() {
    std::setlocale(LC_COLLATE, "");

    const char* label = "Resume";
    const char* token = "GET";

    std::cout << std::boolalpha;
    std::cout << "Label match: " << stringsMatch(label, "resume", Kind::UserLabel) << "\n";
    std::cout << "Token match: " << stringsMatch(token, "get", Kind::ProtocolToken) << "\n";

    return 0;
}

How It Works

User-visible labels may use locale rules; HTTP methods and command tokens must match exact bytes with strcmp. Mixing them up causes subtle bugs.

🚀 Common Use Cases

  • Sorting contact names — address books and directory lists for end users.
  • Localized UI lists — menu items and settings sorted per language.
  • Database-less reports — order strings on the client using OS locale rules.
  • Internationalization learning — understand why raw ASCII sort fails for global text.
  • Comparator for C APIs — pass to qsort when locale order is required.

🧠 How strcoll() Works

1

Locale is active

setlocale(LC_COLLATE, ...) selects collation rules for the process.

Locale
2

Collation engine runs

Characters are compared using locale tables—not simple unsigned byte subtraction.

Collation
3

Ordering decision

Rules for case, accents, and language-specific order determine which string comes first.

Rules
=

Return sign

Negative, zero, or positive—same interpretation as strcmp, different meaning behind the order.

📝 Notes

  • Results depend on the active locale—document or set it explicitly in programs that must behave consistently.
  • If setlocale fails, fall back gracefully; do not assume UTF-8 locale names exist on every machine.
  • Both strings must be valid null-terminated UTF-8 (or encoding matching the locale).
  • strcoll is typically slower than strcmp because locale tables are consulted.
  • For heavy i18n, modern apps often use ICU or platform APIs; strcoll is the portable C-library baseline.

⚡ Optimization

Use strcmp for internal keys and protocol identifiers where locale rules are wrong or expensive. Reserve strcoll for user-visible sorting and searching. If you sort the same large list repeatedly, sort once and cache the result rather than calling strcoll on every UI refresh.

Conclusion

strcoll() brings locale-aware ordering to C-string comparison. Pair it with setlocale(LC_COLLATE, ...), interpret return signs like strcmp, and use it when humans care about sort order—not when machines compare exact tokens.

Next, learn strcpy() to copy C-strings into buffers—a fundamental building block alongside compare and search functions.

💡 Best Practices

✅ Do

  • Call setlocale(LC_COLLATE, ...) before strcoll
  • Use strcoll for user-facing sorted lists
  • Check whether setlocale succeeded
  • Keep using strcmp for exact token matching
  • Document locale assumptions in your program

❌ Don’t

  • Sort usernames with strcmp when locale order matters
  • Compare HTTP verbs with strcoll
  • Assume identical output on every OS without testing
  • Ignore encoding/locale mismatch (Latin-1 vs UTF-8)
  • Rely on exact non-zero return values—use sign only

Key Takeaways

Knowledge Unlocked

Five things to remember about strcoll()

Use these points when comparing strings for people, not machines.

5
Core concepts
02

setlocale

Configure rules.

Setup
🔢 03

Sign Return

Like strcmp.

Return
📈 04

vs strcmp

Locale vs bytes.

Compare
👥 05

User Lists

Names & menus.

Use case

❓ Frequently Asked Questions

strcoll() compares two null-terminated C-strings using the current locale's collation rules—not raw byte/ASCII order. It returns an int whose sign indicates whether str1 is less than, equal to, or greater than str2 under those rules.
int strcoll(const char* str1, const char* str2); Include <cstring>. Call setlocale(LC_COLLATE, "") or another locale before comparing if you need locale-specific ordering.
strcmp() compares characters by their code unit values (lexicographic/ASCII-like order). strcoll() respects locale collation—accent ordering, case rules, and language-specific alphabet order may differ from strcmp().
Same convention as strcmp: 0 if equal under collation rules, less than 0 if str1 sorts before str2, greater than 0 if str1 sorts after str2. Only the sign is portable.
Yes for meaningful locale behavior. setlocale(LC_COLLATE, "") selects the user's environment locale. Without setting LC_COLLATE, results may fall back to behavior similar to strcmp depending on platform.
Learn strcoll() when you sort or compare names for users in different languages. For most new C++ app code, std::string with std::locale-aware tools (or platform i18n libraries) is easier—but strcoll() teaches how C handles locale collation.
Did you know?

The C locale category LC_COLLATE affects only comparison and sorting functions like strcoll and strxfrm. Other categories control number formats (LC_NUMERIC) and time formats (LC_TIME) separately.

Continue the String Functions Series

Learn locale-aware comparison with strcoll(), then copy strings with strcpy().

Next: strcpy() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful