Skip to content

Instantly share code, notes, and snippets.

@TheDcoder
Last active July 6, 2019 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheDcoder/3d573d65b7bd9dd7b42e3a9993c68355 to your computer and use it in GitHub Desktop.
Save TheDcoder/3d573d65b7bd9dd7b42e3a9993c68355 to your computer and use it in GitHub Desktop.
strseg - Get delimiter-separated segments from a string in a non-destructive method
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "segstr.h"
int main(void) {
char *string = "The Quick Brown Fox Jumped Over The Lazy Dog";
char *segment = string;
size_t segment_len;
unsigned int segment_num = 0;
while (true) {
segment = segstr(segment, &segment_len, ' ', &segment_num);
if (!segment) {
puts("Printed all of the words in the sentence!");
return EXIT_SUCCESS;
}
// Skip the word "The"
if (segequstr(segment, segment_len, "The")) continue;
printf("Word No. %u in sentence: %.*s\n", segment_num, (int) segment_len, segment);
}
}
#include <stdbool.h>
#include <string.h>
/// @brief Get delimiter-separated segments from a string in a non-destructive method.
/// @details A useful function which can be used for parsing in a loop in a safe manner.
/// @author Damon Harris (TheDcoder@protonmail.com)
/// @param [in] str Current segment or start of the string.
/// @param [in,out] seg_len Length of the current segment, value does not matter if `seg_num` is set to 0.
/// @param delim Character used for separation (delimiter).
/// @param [in,out] seg_num Number of the current segment, set to 0 before first call.
/// @returns Pointer to the start of the next segment, `seg_len` is set to the length of the segment and `seg_num` is incremented by 1.
/// NULL if there is no next segment, note that NULL is never returned on the first call (even if an empty string is passed).
/// @remarks `seg_num` only has significance if its value is 0, the reason is for the function to be able to detect the initial call
/// so that it doesn't skip the first segment. `seg_len` can be any value on the first call since it is not used to calculate
/// the start of the next segment.
///
/// I was inspired by the lack of a helper function which I can use for parsing/tokenizing a string which is both stateless
/// and non-destructive (`strtok_s` is better than `strtok` but still modifies the supplied string). The best alternative was to
/// `strchr` and keep track of other stuff manually, this function tries to give out as much information as possible while keeping
/// the overall concept simple. The length and position (number) of the segment should be enough to get you started on parsing :)
char *segstr(const char *str, size_t *seg_len, char delim, unsigned int *seg_num) {
if (*seg_num != 0) {
// Check if we have reached the last segment
str += *seg_len;
if (str[0] == '\0') return NULL;
// Proceed to the next segment
++str;
}
// Increment the segment number
++*seg_num;
// Find the delimiter
char *delim_start = strchr(str, delim);
// Calculate the length of the segment
if (delim_start) {
// Difference between the delimiter and the start of the segment
*seg_len = delim_start - str;
} else {
// We have reached the last segment
// There is no delimiter, so use the remaining length
*seg_len = strlen(str);
}
// Return the segment
return (char *) str;
}
/// @brief Check a segment for equality with a string
/// @author Jan Alexander Steffens (jan.steffens@gmail.com)
/// @param seg Segment to test for equality.
/// @param seg_len Length of the segment.
/// @param str String to match with the segment.
/// @returns `true` if `str` is equal to `seg`, otherwise `false`.
/// @remarks This function was made as a convenience alternative to `strncmp`.
/// I would like to thank heftig from the ##c IRC channel at freenode for coming up with the code based on my concept!
bool segequstr(char *seg, size_t seg_len, char *str) {
return strncmp(seg, str, seg_len) == 0 && str[seg_len] == '\0';
}
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment