Library contents

C strlen

Count the units in a plain ASCII parcel code before checking its expected length.

A simple example

strlen

  1. Start with "abc"
  2. Do this Count the characters
  3. Result 3
Count a, then b, then c. These simple ASCII characters each count as one here.
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *value = "abc";
    printf("%ld\n", (long) (strlen(value)));
    return 0;
}
Output
3

Syntax

C syntax
strlen(label)
Run these examples in C

Save one example at a time as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Check the length of a parcel code

A warehouse label uses a compact parcel identifier containing punctuation. Count the stored units across the entire identifier before testing it against the importer's length requirement.

From the programconst char *label = "PK-407"
Result6
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *label = "PK-407";
    printf("%ld\n", (long) (strlen(label)));
    return 0;
}
Output
6

The two letters, hyphen, and three digits make six units.

Advertisements

Count characters in a train ticket code

A railway prints a prefix, a hyphen and digits as one ticket code. Include the separator when measuring the code so the validation matches the complete printed identifier.

From the programconst char *value = "T-204"
Result5
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *value = "T-204";
    printf("%ld\n", (long) (strlen(value)));
    return 0;
}
Output
5

The hyphen is counted along with the letter and digits.

Measure an unused booking code

A registration service checks the length of a short identifier before accepting it. Include every stored unit in the count and consider what the validation sees when no characters were supplied.

From the programconst char *value = ""
Result0
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *value = "";
    printf("%ld\n", (long) (strlen(value)));
    return 0;
}
Output
0

An empty code has no units to count.

What to watch for

Byte counts, UTF-16 code units, Unicode code points, and displayed characters can differ outside ASCII.

Documentation for strlen