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
- Start with A followed by a newline
- Do this Count up to the first line ending
- Result 1
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.
#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;
}
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
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?
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?