libc: Implement strspn (with a test)

This commit is contained in:
apio 2022-10-22 12:36:31 +02:00
parent 551d731627
commit 9bbb5d0c07
4 changed files with 51 additions and 0 deletions

View File

@ -51,6 +51,9 @@ extern "C"
/* 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);
/* Returns the length of the initial segment of str which consists entirely of bytes in accept. */
size_t strspn(const char* str, const char* accept);
/* Compares strings a and b. You might prefer to use the safer strncmp function. */
int strcmp(const char* a, const char* b);

View File

@ -135,6 +135,28 @@ extern "C"
return s - str;
}
size_t strspn(const char* str, const char* accept)
{
const char* s = str;
while (*s)
{
const char* ap = accept;
bool match = false;
while (*ap)
{
if (*s == *ap)
{
match = true;
break;
}
ap++;
}
if (!match) return s - str;
s++;
}
return s - str;
}
char* strcat(char* dest, const char* src)
{
size_t dest_len = strlen(dest);

View File

@ -3,6 +3,7 @@
DEFINE_TEST(strlen);
DEFINE_TEST(strnlen);
DEFINE_TEST(strcspn);
DEFINE_TEST(strspn);
DEFINE_TEST(atoi);
DEFINE_TEST(atol);
@ -15,6 +16,7 @@ int main()
RUN_TEST(strlen);
RUN_TEST(strnlen);
RUN_TEST(strcspn);
RUN_TEST(strspn);
START_TEST_CASE(stdlib.h);
RUN_TEST(atoi);

View File

@ -59,5 +59,29 @@ DEFINE_TEST(strcspn)
EXPECT_EQ(len, 5);
TEST_SUCCESS();
}
DEFINE_TEST(strspn)
{
START_TEST(strspn);
const char* str = "This is a test string";
const char* accept = "This ";
size_t len = strspn(str, accept);
EXPECT_EQ(len, 8);
str = "WWWWW";
len = strspn(str, accept);
EXPECT_EQ(len, 0);
str = "This is hi";
len = strspn(str, accept);
EXPECT_EQ(len, 10);
TEST_SUCCESS();
}