Files
lab_0.1/str.c
2025-11-29 04:15:43 -05:00

189 lines
3.2 KiB
C

#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include "str.h"
#include "util.h"
#define INIT_SZ 20
void
_str_ensure(str *s, int newsz)
{
int tmp;
newsz += 1;
if (newsz < s->capacity)
return;
tmp = s->capacity * 2;
if (tmp > newsz) {
newsz = tmp;
}
s->ptr = xrealloc(s->ptr, newsz);
s->capacity = newsz;
}
void
str_init(str *s)
{
assert(s);
s->len = 0;
s->capacity = INIT_SZ;
s->ptr = xmalloc(INIT_SZ);
s->ptr[0] = '\0';
}
void
str_deinit(str *s)
{
if (s->ptr)
free(s->ptr);
s->ptr = NULL;
s->len = 0;
s->capacity = 0;
}
void
str_init_data(str *s, const char *initial)
{
assert(s && initial);
int len = strlen(initial);
s->len = len;
s->capacity = len + 1;
s->ptr = xmalloc(len + 1);
strcpy(s->ptr, initial);
}
char *
str_data(str *s)
{
assert(s);
return s->ptr;
}
void
str_set(str *s, char *cstr)
{
assert(s && cstr);
int len = strlen(cstr);
_str_ensure(s, len);
strcpy(s->ptr, cstr);
s->len = len;
}
str
str_copy(str *s)
{
assert(s);
str s2;
str_init_data(&s2, s->ptr);
return s2;
}
int
str_count(str *s, char ch)
{
assert(s);
int count = 0;
for (int i = 0; i < s->len; i++)
{
if (s->ptr[i] == ch)
{count++;}
}
return count;
}
void
str_append(str *s, char *cstr)
{
assert(s && cstr);
str_append_n(s, cstr, strlen(cstr));
}
void
str_append_n(str *s, char *cstr, int len)
{
assert(s && cstr);
_str_ensure(s, s->len + len);
memcpy(s->ptr + s->len, cstr, len);
s->len += len;
s->ptr[s->len] = '\0';
}
void
str_shrink(str *s, int len)
{
assert(s && len >= 0);
if (len > s->len)
{return;}
s->len = len;
s->ptr[s->len] = '\0';
}
int
str_find(str *s, char *substr)
{
assert(s && substr);
char *p = strstr(s->ptr, substr);
if (p == NULL)
return -1;
return p - s->ptr;
}
str
str_sub(str *s, int start_idx, int length)
{
assert(s && start_idx >= 0 && length >= 0);
str s2;
str_init(&s2);
if (start_idx >= s->len)
{return s2;}
int true_length = length;
if (start_idx + length > s->len)
{true_length = s->len - start_idx;}
_str_ensure(&s2, true_length);
memcpy(s2.ptr, s->ptr + start_idx, true_length);
s2.len = true_length;
s2.ptr[true_length] = '\0';
return s2;
}
int
str_replace(str *s, char *substr, char *replacement)
{
assert(s && substr && replacement);
int count = 0;
str replaced;
str_init(&replaced);
char *current = s->ptr;
char *found;
int substr_len = strlen(substr);
int replacement_len = strlen(replacement);
while ((found = strstr(current, substr)) != NULL)
{
int prefix_len = found - current;
if (prefix_len > 0)
{str_append_n(&replaced, current, prefix_len);}
str_append_n(&replaced, replacement, replacement_len);
current = found + substr_len;
count++;
}
if (*current != '\0') {
str_append(&replaced, current);
}
str_set(s, replaced.ptr);
str_deinit(&replaced);
return count;
}