Obtaining a string's length - the number of characters it currently stores - is a basic string operation. String objects support the dot operator, and most string classes provide a length function. However, C-strings, like all fundamental types, do not support the dot operator. In place of the .length() function defined by most string classes, the standard C-string library provides the strlen function, which counts and returns the number of characters in a C-string. The function does not count the null termination character or any characters following it.
strlen: String-Length
strlen(s)
#include <cstring>size_t strlen(const char* str);size_t strnlen(const char *str, size_t maxlen); 1size_t strnlen_s(const char *str, size_t numberOfElements);s.length()
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char* s = "EXAMPLE";
cout << strlen(s) << endl;
char s[0] = '\0';
cout << strlen(s) << endl;
return 0;
} |
|
Output: 7 0 |
Implementing a string as a fundamental data type involves balancing conflicting goals. C-strings prioritize structural simplicity and passing efficiency at the expense of some operations running more slowly. The C-string strlen counts the characters to obtain the string's length, resulting in a linear runtime. Fortunately, the counting loop is small and consists of a few machine instructions. Furthermore, optimizing compilers typically cache the function's return value (e.g., when driving a loop) if the string doesn't change. Programmers can implement the counting loop in many ways.
int strlen(const char* s)
{
int len = 0;
while (s[len])
len++;
return len;
} |
int strlen(const char* s)
{
int len = 0;
while (*(s+len))
len++;
return len;
} |
| (a) | (b) |
int strlen(const char* s)
{
int len = 0;
for (; s[len]; len++)
;
return len;
} |
int strlen(const char* s)
{
int len = 0;
for (; *(s+len); len++)
;
return len;
} |
| (c) | (d) |
Versions (a) and (c) use an indexing notation that may be more familiar and easier to understand. The (b) and (d) versions use address arithmetic and the dereference operator.