summaryrefslogtreecommitdiff
path: root/c/dataStructure/string/string.c
blob: 5b48917f81019bcc14bbb75cd14ceff9878be63f (plain)
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
#include "string.h"

void StrAssign(sstring * st, const char * ch)
{
    size_t size = strlen(ch);

    st->s = (char *) malloc (sizeof(char) * (size+1));

    if (!st->s)
    {
        fprintf(stderr,"Failed to malloc!\n");
        exit(EXIT_FAILURE);
    }
    
    strncpy(st->s,ch,size+1);
    st->length = size;
}

void StrCopy(sstring * st, const sstring * sp)
{
    if (!sp->s)
    {
        fprintf(stderr,"Empty string!\n");
        exit(EXIT_FAILURE);
    }

    StrAssign(st,sp->s);
}

bool StrEmpty(sstring * st)
{
    if (!st->s)
        return false;
    return true;
}

int StrCompare(const sstring * st, const sstring * sp)
{
    int count = 0, i;
    if (!st->s || !sp->s)
    {
        fprintf(stderr,"Empty string!\n");
        exit(EXIT_FAILURE);
    }

    for (i = 0; st->s[i] && sp->s[i]; i++)
    {
        if (st->s[i] > sp->s[i])
            count++;
        else if (st->s[i] < sp->s[i])
            count--;
    }

    if (st->s[i])
    {
        i++;
        count++;
    }
    else if (sp->[i])
    {
        i++;
        count--;
    }

    return count;
}