comparison th_string.c @ 674:dfabc7eef3dd

Add new functions th_split_string() and th_join_string().
author Matti Hamalainen <ccr@tnsp.org>
date Tue, 25 Feb 2020 05:16:42 +0200
parents 4932188c9101
children 83a48de05fe9
comparison
equal deleted inserted replaced
673:1763d9b26a58 674:dfabc7eef3dd
549 if ((*pdst = th_malloc((slen + 1) * sizeof(th_char_t))) == NULL) 549 if ((*pdst = th_malloc((slen + 1) * sizeof(th_char_t))) == NULL)
550 return THERR_MALLOC; 550 return THERR_MALLOC;
551 551
552 memcpy(*pdst, src, (slen + 1) * sizeof(th_char_t)); 552 memcpy(*pdst, src, (slen + 1) * sizeof(th_char_t));
553 } 553 }
554
555 return THERR_OK;
556 }
557
558
559 int th_split_string(const th_char_t *str, th_char_t ***elems, size_t *nelems, const th_char_t *sep)
560 {
561 size_t start = 0, end;
562 BOOL match = FALSE;
563
564 if (elems == NULL || nelems == NULL)
565 return THERR_NULLPTR;
566
567 *elems = NULL;
568 *nelems = 0;
569
570 do
571 {
572 // Split foremost str element out
573 match = FALSE;
574 for (end = start; str[end] != 0; end++)
575 if (strchr(sep, str[end]) != NULL)
576 {
577 match = TRUE;
578 break;
579 }
580
581 // If the element is there, create it
582 if (str[start] != 0 && end >= start)
583 {
584 th_char_t *elem = th_strndup(str + start, end - start);
585 if (elem == NULL)
586 return THERR_MALLOC;
587
588 if ((*elems = th_realloc(*elems, sizeof(th_char_t **) * (*nelems + 1))) == NULL)
589 return THERR_MALLOC;
590
591 (*elems)[*nelems] = elem;
592 (*nelems)++;
593 }
594
595 start = end + 1;
596 } while (match);
597
598 return THERR_OK;
599 }
600
601
602 int th_join_string(th_char_t **str, th_char_t **elems, const size_t nelems, const th_char_t *sep)
603 {
604 size_t len, n, offs, seplen, *elemlens;
605
606 if (elems == NULL || str == NULL || sep == NULL)
607 return THERR_NULLPTR;
608
609 if ((elemlens = th_malloc(nelems * sizeof(size_t))) == NULL)
610 return THERR_MALLOC;
611
612 seplen = strlen(sep);
613
614 for (len = n = 0; n < nelems; n++)
615 {
616 len += elemlens[n] = strlen(elems[n]);
617 }
618
619 len += 1 + n * seplen;
620
621 if ((*str = th_malloc(len)) == NULL)
622 {
623 th_free(elemlens);
624 return THERR_MALLOC;
625 }
626
627 for (offs = n = 0; n < nelems; n++)
628 {
629 if (n > 0)
630 {
631 memcpy((*str) + offs, sep, seplen);
632 offs += seplen;
633 }
634
635 memcpy((*str) + offs, elems[n], elemlens[n]);
636 offs += elemlens[n];
637 }
638
639 (*str)[offs] = 0;
554 640
555 return THERR_OK; 641 return THERR_OK;
556 } 642 }
557 643
558 644