Library contents

C strlen

Check whether an optional text field contains zero characters.

A simple example

strlen

  1. Start with ""
  2. Do this Check whether any characters exist
  3. Result Empty
This string has length zero. A string containing one space has length one.
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *value = "";
    printf("%s\n", (strlen(value) == 0) ? "yes" : "no");
    return 0;
}
Output
yes

Syntax

C syntax
strlen(value) == 0
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 for an untouched delivery note

A form can look blank even when its field contains a space. Examine the stored input before marking the answer as missing, because an empty string and whitespace can require separate checks.

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

int main(void) {
    const char *value = "";
    printf("%s\n", (strlen(value) == 0) ? "yes" : "no");
    return 0;
}
Output
yes

A new empty field contains no text.

Advertisements

Check a student answer containing one space

An examination form receives a response consisting of a single space. Determine whether the raw field is empty before deciding whether the student has supplied a meaningful answer.

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

int main(void) {
    const char *value = " ";
    printf("%s\n", (strlen(value) == 0) ? "yes" : "no");
    return 0;
}
Output
no

Even a single space makes the string nonempty.

Accept a written handover

A night worker types a short handover message. The clerk first checks whether the field contains any characters at all. Is the supplied field empty?

Given“Done”
Worked resultHas text

What to watch for

A space is still a character. Use a whitespace check if a spaces-only entry should be rejected.

Documentation for strlen