Library contents

C strcspn

strcspn counts the initial bytes of a string that contain none of the rejected bytes. Searching for carriage return and newline finds the end of a text record.

A simple example

strcspn

  1. Start with A followed by a newline
  2. Do this Count up to the first line ending
  3. Result 1
Only A appears before the newline. Its length gives the position where the ending begins.

Syntax

C syntax
size_t strcspn(const char *text, const char *reject)
Run this example in C

Save the program as lesson.c. Use C17 and a Unix-style shell.

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

Remove either kind of line ending

A file import receives lines saved on machines with different line endings. Remove the line terminator while preserving the actual field text, including spaces that may belong to the record.

From the programchar lines[][16] = {"north\r\n", "south"}
First output linenorth
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char lines[][16] = {"north\r\n", "south"};
    for (size_t i = 0; i < 2; ++i) {
        lines[i][strcspn(lines[i], "\r\n")] = '\0';
        puts(lines[i]);
    }
    return 0;
}
Output
north
south

When the line contains neither delimiter, strcspn returns its full length. Writing the terminator there is safe for this writable, null-terminated array.

Open Group function reference for strcspn

Advertisements

Read a Windows label row

A desk imports a badge followed by a CRLF pair. The input record ends at the first carriage return or line feed. Which text precedes that boundary?

GivenLAB-5 + CRLF
Worked resultLAB-5

Keep a final row

A meter sends a final label without a terminator. The input record ends at the first carriage return or line feed. Which text precedes that boundary?

GivenDock + end of input
Worked resultDock