std::strlen(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸŽ€ NAME πŸŽ€

okay bestie, welcome to the std::strlen(3) page from the C++ Standard Libary manual πŸ’…. The name is literally std::strlen - std::strlen (yes, that's the whole NAME section, no cap). We're gonna get you comfy with it.

✨ Synopsis ✨

Defined in header <cstring>:

std::size_t strlen( const char* str );

So std::strlen returns the length of the given byte string β€” that's the number of characters in a character array whose first element is pointed to by str, up to and not including the first null character 🫢. The behavior is undefined if there is no null character in the character array pointed to by str 😭. Like, fr fr, do not let that happen.

🌸 Parameters 🌸

  • str β€” pointer to the null-terminated byte string to be examined πŸ”

πŸ’– Return value πŸ’–

The length of the null-terminated string str ✨.

πŸ¦‹ Possible implementation πŸ¦‹

Here's the possible implementation, bestie β€” copy the shape, not my whole personality:

std::size_t strlen(const char* start)
{
    // NB: start is not checked for nullptr!
    const char* end = start;
    while (*end != '\0')
        ++end;
    return end - start;
}

πŸ“ Example πŸ“

// Run this code

#include <cstring>
#include <iostream>

int main()
{
    const char str[] = "dog cat\0mouse";

    std::cout << "without null character: " << std::strlen(str) << '\n'
              << "with null character: " << sizeof str << '\n';
}

πŸ’» Output:

without null character: 7
with null character: 14

πŸ‘‘ See also πŸ‘‘

  • wcslen β€” returns the length of a wide string (function) 🌈
  • mblen β€” returns the number of bytes in the next multibyte character (function) 🧚
  • C documentation for strlen πŸ“š

Source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::strlen(3) πŸ’œ

πŸ“¦ where this page comes from