Regardless of how we implement a string, determining how many characters are in it is one of the most basic string operations. The strlen function counts and returns the number of characters in a C-string. Note that it does not include in the count either the null termination character or any characters between the null termination and the end of the character array. Also note that, unlike Java strings, you cannot use .length() to determine the length of a C-string.
#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 |
int strlen(const char* s) { int len = 0; while (s[len]) // '\0' ends the loop len++; return len; } |
int strlen(const char* s) { int len = 0; while (*(s++)) // '\0' ends the loop len++; return len; } |
(a) | (b) |
int strlen(const char* s) { int i = 0; for (; s[i]; i++) ; return i; } |
int strlen(const char* s) { int i = 0; for (; *(s+i); i++) ; return i; } |
(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 the dereference operator. Note that version (b) changes the value stored in s; for this reason, the program cannot use s for any other string operations after the loop.