summaryrefslogtreecommitdiff
path: root/c/dataStructure/string
diff options
context:
space:
mode:
Diffstat (limited to 'c/dataStructure/string')
-rwxr-xr-xc/dataStructure/string/main.c15
-rwxr-xr-xc/dataStructure/string/string.c66
-rwxr-xr-xc/dataStructure/string/string.h19
3 files changed, 100 insertions, 0 deletions
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 <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdbool.h>
+
+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