libc: Implement strspn (with a test)
This commit is contained in:
parent
551d731627
commit
9bbb5d0c07
@ -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);
|
||||
|
||||
|
@ -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);
|
||||
|
@ -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);
|
||||
|
@ -61,3 +61,27 @@ DEFINE_TEST(strcspn)
|
||||
|
||||
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();
|
||||
}
|
Loading…
Reference in New Issue
Block a user