User Tools

Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

c:string [2019-05-28 15:26] (current)
Line 1: Line 1:
 +
 +<code C string.c>​
 +/*
 + * Copyright 2004-2019 Oleg Borodin ​ <​borodin@unix7.org>​
 + */
 +
 +#include <​stdarg.h>​
 +#include <​stdio.h>​
 +#include <​stdlib.h>​
 +#include <​string.h>​
 +
 +#define STRING_INIT_CAPACITY 4
 +
 +void debug_printf(char *format, ...) {
 +   ​va_list args;
 +   ​va_start(args,​ format);
 +   ​vfprintf(stderr,​ format, args);
 +   ​va_end(args);​
 +}
 +
 +typedef struct string {
 +    char* items;
 +    int capacity;
 +    int size;
 +} string_t;
 +
 +void string_init(string_t* s) {
 +    s->​capacity = STRING_INIT_CAPACITY;​
 +    s->size = 0;
 +    s->items = malloc(sizeof(char) * s->​capacity);​
 +}
 +
 +int string_size(string_t *s) {
 +    return s->size;
 +}
 +
 +void string_resize(string_t *s, int capacity) {
 +    void* items = realloc(s->​items,​ sizeof(char) * capacity);
 +    if (items) {
 +        s->items = (char*)items;​
 +        s->​capacity = capacity;
 +    }
 +}
 +
 +void string_add(string_t *s, char item) {
 +    if (s->​capacity == s->size) {
 +        string_resize(s,​ s->​capacity * 2);
 +    }
 +    s->​items[s->​size++] = item;
 +}
 +
 +void string_set(string_t* s, int index, char item) {
 +    if (index >= 0 && index < s->size) {
 +        s->​items[index] = item;
 +    }
 +}
 +
 +char string_get(string_t* s, int index) {
 +    if (index >= 0 && index < s->size) {
 +        return s->​items[index];​
 +    }
 +    return 0;
 +}
 +
 +char* string_getstr(string_t* s) {
 +
 +    string_resize(s,​ s->size + 1);
 +    string_set(s,​ s->size + 1, 0);
 +    return s->​items;​
 +}
 +
 +void string_addstr(string_t *s, char* str) {
 +    int slen = strlen(str);​
 +    string_resize(s,​ s->size + slen);
 +    for (int i = 0; i < slen; i++) {
 +        s->​items[s->​size + i] = str[i];
 +    }
 +    s->size += slen;
 +}
 +
 +char* string_getistr(string_t* s, int index) {
 +    if (index < 0 || index > s->size) {
 +        return NULL;
 +    }
 +    string_resize(s,​ s->size + 1);
 +    string_set(s,​ s->size + 1, 0);
 +    return &​(s->​items[--index]);​
 +}
 +
 +void string_delete(string_t *s, int index) {
 +    if (index < 0 || index >= s->size) {
 +        return;
 +    }
 +    for (int i = index; i < s->size - 1; i++) {
 +        s->​items[i] = s->​items[i + 1];
 +    }
 +    s->​size--;​
 +
 +    if (s->size > 0 && s->size == s->​capacity / 4) {
 +        string_resize(s,​ s->​capacity / 2);
 +    }
 +}
 +
 +void string_free(string_t *s) {
 +    free(s->​items);​
 +    s->size = 0;
 +    s->​capacity = 0;
 +}
 +
 +int main(int argc, char **argv) {
 +
 +    string_t s;
 +    string_init(&​s);​
 +    //​string_add(&​s,​ '​a'​);​
 +    //​string_add(&​s,​ '​b'​);​
 +    string_addstr(&​s,​ "​0123456789"​);​
 +    printf("​%s\n",​ string_getistr(&​s,​ 3));
 +
 +    return 0;
 +}
 +</​code>​