67 lines
1.4 KiB
C
67 lines
1.4 KiB
C
#include "my_strings.h"
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
//' -> ' est un racc pour *rslt.data
|
|
struct string *my_str_init(const char* s, size_t size){
|
|
|
|
struct string *rslt = malloc(sizeof(struct string));
|
|
if(rslt == NULL) return NULL;
|
|
|
|
if(size == 0 || s == NULL) {
|
|
rslt->data = NULL;
|
|
rslt->size = 0;
|
|
}
|
|
else{
|
|
rslt->data = malloc(size);
|
|
if(rslt->data == NULL){
|
|
free(rslt);
|
|
return NULL;
|
|
}
|
|
|
|
memcpy(rslt->data, s, size);
|
|
rslt->size = size;
|
|
}
|
|
return rslt;
|
|
}
|
|
|
|
void my_str_destroy(struct string *str){
|
|
|
|
if(str == NULL) return;
|
|
|
|
free(str->data);
|
|
free(str);
|
|
}
|
|
|
|
void my_str_puts(struct string *str){
|
|
|
|
if(str == NULL) return;
|
|
|
|
|
|
if(str->data == NULL || str->size == 0)printf("\n");
|
|
|
|
for (size_t i = 0; i < str->size; i++) putchar(*((str->data) + i));
|
|
}
|
|
|
|
struct string *my_str_n_cat(struct string *str1, const char *str2, size_t str2_len){
|
|
|
|
if (str2 == NULL || str2_len == 0) return str1;
|
|
|
|
if (str1 == NULL){
|
|
struct string *rslt = my_str_init(str2, str2_len);
|
|
return rslt;
|
|
}
|
|
|
|
str1->data = realloc(str1->data, (str1->size + str2_len) * sizeof(char));
|
|
if(str1 == NULL) return str1;
|
|
|
|
//printf("test");
|
|
int index = 0;
|
|
while (*(str2 + index)){
|
|
str1->data[str1->size + index] = str2[index];
|
|
index ++;
|
|
}
|
|
str1->size = str1->size + index;
|
|
return str1;
|
|
}
|