Home > database >  C how to make a scanset stop when at certain length or when reading specific char
C how to make a scanset stop when at certain length or when reading specific char

Time:12-15

I have a string that consists of 3 parts (start, middle, end).
The middle part is encapsulated in '' and it always contains one char or more (could be several hundred).
I want to only store the first 15 chars of this part if it's longer than 15 chars. Otherwise, I can just store the whole part.

char result1[16], result2[16];
char *str1 = "placeholder 'this is more than 15 chars' placeholder";
char *str2 = "placeholder 'this is less' placeholder";

sscanf(str1, "%*[^']'[^']'%*[^']", result1);
sscanf(str2, "%*[^']'[^']'%*[^']", result2);

printf("|%s|", result1);
printf("|%s|", result2);

//Expected output result1: "|this is more th|"
//Expected output result2: "|this is less|"

Keep in mind I am interested in one sscanf to handle both cases.
The above example might appear to work, but sometimes in the case of str2 the scanset will continue to eat all 15 chars even if it has met its delimiter '.

Is there a way to make the scanset stop at its delimiter only if it has eaten less than 15 chars?

CodePudding user response:

Consider a more robust alternative with error checking.

char *get_middle(char *dest, size_t sz, const char *s) {
  if (dest == NULL || sz == 0) return NULL;
  char *first = strchr(s, '\''); 
  if (first == NULL) return NULL;
  first  ;
  char *second = strchr(first, '\''); 
  if (second == NULL) return NULL;
  size_t len = second - first;
  if (len == 0) return NULL;
  if (len >= sz) len = sz - 1;
  dest[len] = 0; 
  return memcpy(dest, first, len);
}
  • Related