string: split strcmp and strncmp (DONE)

This commit is contained in:
Lephenixnoir 2021-05-23 17:04:08 +02:00
parent ab8bcc6928
commit d5ef8298ae
No known key found for this signature in database
GPG key ID: 1BBA026E13FC0495
3 changed files with 12 additions and 30 deletions

View file

@ -142,6 +142,7 @@ set(SOURCES
src/libc/string/strcpy.c
src/libc/string/strdup.c
src/libc/string/strlen.c
src/libc/string/strncmp.c
src/libc/string/strnlen.c
src/libc/string/strrchr.c)

View file

@ -1,40 +1,10 @@
#include <string.h>
/*
** The strcmp() function compares the two strings s1 and s2. The locale is not
** taken into account (for a locale-aware comparison, see strcoll(3)).
** The comparison is done using unsigned characters.
**
** strcmp() returns an integer indicating the result of the comparison, as follows:
** * 0, if the s1 and s2 are equal;
** * a negative value if s1 is less than s2;
** * a positive value if s1 is greater than s2.
**
** TODO: quad-word access !
*/
int strcmp(const char *s1, const char *s2)
{
if (s1 == NULL || s2 == NULL)
return (0);
while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2) {
s1 += 1;
s2 += 1;
}
return (*s1 - *s2);
}
/*
** The strncmp() function is similar, except it compares only the first (at most)
** n bytes of s1 and s2.
**
** TODO: quad-word access !
*/
int strncmp(const char *s1, const char *s2, size_t n)
{
if (s1 == NULL || s2 == NULL || n == 0)
return (0);
size_t i = -1;
while (++i < n - 1 && s1[i] != '\0' && s2[i] != '\0'
&& s1[i] == s2[i]) ;
return (s1[i] - s2[i]);
}

11
src/libc/string/strncmp.c Normal file
View file

@ -0,0 +1,11 @@
#include <string.h>
int strncmp(const char *s1, const char *s2, size_t n)
{
if (n == 0)
return (0);
size_t i = -1;
while (++i < n - 1 && s1[i] != '\0' && s2[i] != '\0'
&& s1[i] == s2[i]) ;
return (s1[i] - s2[i]);
}