-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.c
92 lines (81 loc) · 1.98 KB
/
string.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//jednoducha knihovna pro praci s nekonecne dlouhymi retezci
#include <string.h>
#include <malloc.h>
#include "str.h"
#define STR_LEN_INC 8
// konstanta STR_LEN_INC udava, na kolik bytu provedeme pocatecni alokaci pameti
// pokud nacitame retezec znak po znaku, pamet se postupne bude alkokovat na
// nasobky tohoto cisla
#define STR_ERROR 1
#define STR_SUCCESS 0
int strInit(void *s)
// funkce vytvori novy retezec
{
if ((s->data = (char*) malloc(STR_LEN_INC)) == NULL)
return STR_ERROR;
s->data[0] = '\0';
s->used = 0;
s->capacity = STR_LEN_INC;
return STR_SUCCESS;
}
void strFree(string *s)
// funkce uvolni retezec z pameti
{
free(s->data);
}
void strClear(string *s)
// funkce vymaze obsah retezce
{
s->data[0] = '\0';
s->used = 0;
}
int strAddChar(string *s1, char c)
// prida na konec retezce jeden znak
{
if (s1->used + 1 >= s1->capacity)
{
// pamet nestaci, je potreba provest realokaci
if ((s1->data = (char*) realloc(s1->data, s1->used + STR_LEN_INC)) == NULL)
return STR_ERROR;
s1->capacity = s1->used + STR_LEN_INC;
}
s1->data[s1->used] = c;
s1->used++;
s1->data[s1->used] = '\0';
return STR_SUCCESS;
}
int strCopyString(Ttoken *s1, string *s2)
// prekopiruje retezec s2 do s1
{
int newused = s2->used;
if (newused >= s1->capacity)
{
// pamet nestaci, je potreba provest realokaci
if ((s1->data = (char*) realloc(s1->data, newused + 1)) == NULL)
return STR_ERROR;
s1->capacity = newused + 1;
}
strcpy(s1->data, s2->data);
s1->used = newused;
return STR_SUCCESS;
}
int strCmpString(Ttoken *s1, string *s2)
// porovna oba retezce a vrati vysledek
{
return strcmp(s1->data, s2->data);
}
int strCmpConstStr(string *s1, char* s2)
// porovna nas retezec s konstantnim retezcem
{
return strcmp(s1->data, s2);
}
char *strGetStr(string *s)
// vrati textovou cast retezce
{
return s->data;
}
int strGetused(string *s)
// vrati delku daneho retezce
{
return s->used;
}