diff --git a/libs/libc/include/string.h b/libs/libc/include/string.h index 86fd2352..d70ebbf6 100644 --- a/libs/libc/include/string.h +++ b/libs/libc/include/string.h @@ -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); diff --git a/libs/libc/src/string.cpp b/libs/libc/src/string.cpp index 6d41c66f..701821c2 100644 --- a/libs/libc/src/string.cpp +++ b/libs/libc/src/string.cpp @@ -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); diff --git a/tests/libc/Test.c b/tests/libc/Test.c index a8156ee9..8b808383 100644 --- a/tests/libc/Test.c +++ b/tests/libc/Test.c @@ -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); diff --git a/tests/libc/string.c b/tests/libc/string.c index 1deed45f..d3c75626 100644 --- a/tests/libc/string.c +++ b/tests/libc/string.c @@ -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(); } \ No newline at end of file