C++ strlen(): Find String Length with a Runnable Example
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
strlen() is a C-style string function declared in the <cstring> header. It accepts a const char* pointer to a null-terminated character array and returns the number of characters before the terminating '\0' as a std::size_t. The terminator itself is not counted.
In the runnable example, text points to "Hello, C++!". Calling std::strlen(text) walks through the characters until it finds the null terminator, producing this output:
String: Hello, C++!
Length: 11
Empty length: 0
Input: a valid, null-terminated C-string. Output: a std::size_t value representing the string length, excluding '\0'. The function does not modify the string. Because it stops at the first null byte, it is not appropriate for binary buffers that may contain embedded nulls. For std::string objects, use .size() or .length() instead. Always pass a valid pointer; passing nullptr or a non-terminated array leads to undefined behavior.
Time complexity: O(n), where n is the number of characters before the null terminator, since every character must be examined. Space complexity: O(1), as only a counter is needed.