From c6bc541ab58363d783e60a007e80e9bf9e231fda Mon Sep 17 00:00:00 2001 From: garhve Date: Mon, 5 Dec 2022 19:43:39 +0800 Subject: initialize --- c/dataStructure/string/main.c | 15 ++++++++++ c/dataStructure/string/string.c | 66 +++++++++++++++++++++++++++++++++++++++++ c/dataStructure/string/string.h | 19 ++++++++++++ 3 files changed, 100 insertions(+) create mode 100755 c/dataStructure/string/main.c create mode 100755 c/dataStructure/string/string.c create mode 100755 c/dataStructure/string/string.h (limited to 'c/dataStructure/string') diff --git a/c/dataStructure/string/main.c b/c/dataStructure/string/main.c new file mode 100755 index 0000000..e0b57d9 --- /dev/null +++ b/c/dataStructure/string/main.c @@ -0,0 +1,15 @@ +#include "string.h" + +int main(void) +{ + sstring st; + char * ch = "This is a test string!"; + + StrAssign(&st,ch); + + printf("ch: %s\nsp: %s\n",ch,st.s); + + free(st.s); + + return 0; +} \ No newline at end of file diff --git a/c/dataStructure/string/string.c b/c/dataStructure/string/string.c new file mode 100755 index 0000000..5b48917 --- /dev/null +++ b/c/dataStructure/string/string.c @@ -0,0 +1,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; +} \ No newline at end of file diff --git a/c/dataStructure/string/string.h b/c/dataStructure/string/string.h new file mode 100755 index 0000000..000f299 --- /dev/null +++ b/c/dataStructure/string/string.h @@ -0,0 +1,19 @@ +#ifndef _STRING_H +#define _STRING_H + +#include +#include +#include +#include + +typedef struct string { + char * s; + int length; +}sstring; + +void StrAssign(sstring * st, const char * ch); +void StrCopy (sstring * st, const sstring * sp); +bool StrEmpty (sstring * st); +int StrCompare(const sstring * st, const sstring * sp); + +#endif \ No newline at end of file -- cgit v1.2.3-70-g09d2