From a3a700a2c045a6d55e40ab92fb9e3f3fb4a60848 Mon Sep 17 00:00:00 2001 From: xavi Date: Sat, 7 Sep 2024 23:26:55 -0700 Subject: [PATCH] Added x_strcmp to compare two strings --- x_string/src/x_string.c | 28 ++++++++++++++++++++++++++++ x_string/src/x_string.h | 1 + 2 files changed, 29 insertions(+) diff --git a/x_string/src/x_string.c b/x_string/src/x_string.c index 6d05b48..01d3436 100644 --- a/x_string/src/x_string.c +++ b/x_string/src/x_string.c @@ -1,6 +1,7 @@ #include #include +// return the length of string to the null terminator int x_strlen(char* str){ char* ptr = str; while(*ptr != '\0'){ @@ -9,6 +10,8 @@ int x_strlen(char* str){ return ptr - str; } +// copy one string to another destination +// must include the size of the destination void x_strcpy(char* dest, char* src, const int size_dest){ char* dest_ptr = dest; char* src_ptr = src; @@ -26,7 +29,32 @@ void x_strcpy(char* dest, char* src, const int size_dest){ } } +// compare two strings +// return 0 if equal to eachother +// return -1 if not +int x_strcmp (char* str1, char* str2){ + char* ptr1 = str1; + char* ptr2 = str2; + while(*ptr1 != '\0' && *ptr2 != '\0'){ + if(*ptr1 != *ptr2){ + return -1; + } + + ptr1++; + ptr2++; + } + + // if havent reached the end of one of the strings + if (*ptr1 != '\0' || *ptr2 != '\0'){ + return -1; + } + + return 0; +} + + +// concatinate two strings char* x_strconcat(char* str1, char* str2){ char* new_string; diff --git a/x_string/src/x_string.h b/x_string/src/x_string.h index 9a4fa11..c3618d9 100644 --- a/x_string/src/x_string.h +++ b/x_string/src/x_string.h @@ -3,6 +3,7 @@ int x_strlen(char*); void x_strcpy(char*, char*, const int); +int x_strcmp(char*, char*); char* x_strconcat(char*, char*); #endif