c / intermediate
Snippet
Precise String Searching with strcspn
The strcspn function calculates the length of the initial segment of a string that consists entirely of characters NOT in a specified set. It is highly efficient for finding the first occurrence of any character from a group of delimiters, returning the index where the first match is found.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>#include <string.h>int main() {const char *csv_line = "data1,data2;data3";const char *delimiters = ",;";// Find length of segment NOT containing delimiterssize_t pos = strcspn(csv_line, delimiters);printf("First delimiter found at index: %zu\n", pos);if (csv_line[pos] != '\0') {printf("Delimiter was: '%c'\n", csv_line[pos]);}return 0;}
Breakdown
1
const char *delimiters = ",;";
Defines a set of characters we want to search for.
2
size_t pos = strcspn(csv_line, delimiters);
Returns the number of characters before any character in 'delimiters' appears.
3
if (csv_line[pos] != '\0')
If the index is less than the string length, a delimiter was actually found.