libc: Add strcspn (with a test)

This commit is contained in:
apio 2022-10-22 11:57:25 +02:00
parent 6816a5b11f
commit 1f5f6a5e3b
4 changed files with 40 additions and 0 deletions

View File

@ -48,6 +48,9 @@ extern "C"
/* Concatenates at most max bytes of the string src into dest. */
char* strncat(char* dest, const char* src, size_t max);
/* Returns the length of the initial segment of str which consists entirely of bytes not in reject. */
size_t strcspn(const char* str, const char* reject);
/* Compares strings a and b. You might prefer to use the safer strncmp function. */
int strcmp(const char* a, const char* b);

View File

@ -119,6 +119,22 @@ extern "C"
return *(const unsigned char*)a - *(const unsigned char*)b;
}
size_t strcspn(const char* str, const char* reject)
{
const char* s = str;
while (*s)
{
const char* rp = reject;
while (*rp)
{
if (*s == *rp) return s - str;
rp++;
}
s++;
}
return s - str;
}
char* strcat(char* dest, const char* src)
{
size_t dest_len = strlen(dest);

View File

@ -2,10 +2,12 @@
DEFINE_TEST(strlen);
DEFINE_TEST(strnlen);
DEFINE_TEST(strcspn);
int main()
{
START_TEST_CASE(string.h);
RUN_TEST(strlen);
RUN_TEST(strnlen);
RUN_TEST(strcspn);
}

View File

@ -42,3 +42,22 @@ DEFINE_TEST(strnlen)
TEST_SUCCESS();
}
DEFINE_TEST(strcspn)
{
START_TEST(strcspn);
const char* str = "This string has vowels";
const char* vowels = "aeiou";
size_t len = strcspn(str, vowels);
EXPECT_EQ(len, 2);
str = "WWWWW";
len = strcspn(str, vowels);
EXPECT_EQ(len, 5);
TEST_SUCCESS();
}