os/string.c

97 lines
1.5 KiB
C
Raw Normal View History

2024-05-21 18:41:16 +03:00
#include "string.h"
#include <stddef.h>
2024-05-22 00:15:05 +03:00
size_t strlen(const char *str)
{
size_t len = 0;
while (str[len])
++len;
return len;
}
void *memset(void *ptr, int value, size_t size)
{
unsigned char *buf = (unsigned char *)ptr;
for (size_t i = 0; i < size; ++i)
buf[i] = (unsigned char)value;
return ptr;
}
2024-05-21 18:41:16 +03:00
int strcmp(const char *str1, const char *str2)
{
while (*str1 && (*str1 == *str2))
{
str1++;
str2++;
}
return *(const unsigned char *)str1 - *(const unsigned char *)str2;
}
2024-05-22 00:15:05 +03:00
char *strchr(const char *str, int character)
2024-05-21 18:41:16 +03:00
{
2024-05-22 00:15:05 +03:00
size_t i = 0;
while (str[i] != (char)character)
2024-05-21 18:41:16 +03:00
{
2024-05-22 00:15:05 +03:00
if (str[i] == '\0')
return NULL;
++i;
2024-05-21 18:41:16 +03:00
}
2024-05-22 00:15:05 +03:00
return (char *)(str + i);
2024-05-21 18:41:16 +03:00
}
char *strtok(char *str, const char *delim)
{
static char *last_token = NULL;
char *token_start;
char *current;
if (str != NULL)
{
current = str;
}
else
{
current = last_token;
}
if (current == NULL)
{
return NULL;
}
while (*current != '\0' && strchr(delim, *current) != NULL)
{
current++;
}
if (*current == '\0')
{
last_token = NULL;
return NULL;
}
token_start = current;
while (*current != '\0' && strchr(delim, *current) == NULL)
{
current++;
}
if (*current != '\0')
{
*current = '\0';
last_token = current + 1;
}
else
{
last_token = NULL;
}
return token_start;
}