forked from xamidev/pepperOS
101 lines
2.5 KiB
C
101 lines
2.5 KiB
C
/*
|
|
* @author xamidev <xamidev@riseup.net>
|
|
* @brief String manipulation utilities
|
|
* @license GPL-3.0-only
|
|
*/
|
|
|
|
#include <stddef.h>
|
|
|
|
/*
|
|
* strcpy - copy a NULL-terminated string
|
|
* @dest: destination buffer where the string is copied
|
|
* @src: source string to copy from
|
|
*
|
|
* Copies the string pointed to by @src (including the terminating
|
|
* NULL byte) into the buffer pointed to by @dest.
|
|
*
|
|
* Return: pointer to the destination string (@dest)
|
|
*/
|
|
char* strcpy(char *dest, const char *src)
|
|
{
|
|
char *temp = dest;
|
|
while((*dest++ = *src++));
|
|
return temp;
|
|
}
|
|
|
|
/*
|
|
* strcat - append a NUL-terminated string
|
|
* @dest: destination buffer containing the initial string
|
|
* @src: source string to append
|
|
*
|
|
* Appends the string pointed to by @src to the end of the string
|
|
* pointed to by @dest. The terminating NUL byte in @dest is
|
|
* overwritten and a new terminating NUL byte is added.
|
|
*
|
|
* The destination buffer must be large enough to hold the result.
|
|
*
|
|
* Taken from: https://stackoverflow.com/questions/2488563/strcat-implementation
|
|
*
|
|
* Return: pointer to the destination string (@dest)
|
|
*/
|
|
char *strcat(char *dest, const char *src)
|
|
{
|
|
size_t i,j;
|
|
for (i = 0; dest[i] != '\0'; i++);
|
|
|
|
for (j = 0; src[j] != '\0'; j++)
|
|
dest[i+j] = src[j];
|
|
|
|
dest[i+j] = '\0';
|
|
return dest;
|
|
}
|
|
|
|
/*
|
|
* strncpy - copy a string with length limit
|
|
* @dst: destination buffer
|
|
* @src: source string
|
|
* @n: maximum number of bytes to copy
|
|
*
|
|
* Copies up to @n bytes from @src to @dst. Copying stops early if a
|
|
* NULL byte is encountered in @src. If @src is shorter than @n, the
|
|
* remaining bytes in @dst are left unchanged in this implementation.
|
|
*
|
|
* Note: This differs slightly from the standard strncpy behavior,
|
|
* which pads the remaining bytes with NULL.
|
|
*
|
|
* Taken from: https://stackoverflow.com/questions/14159625/implementation-of-strncpy
|
|
*/
|
|
void strncpy(char* dst, const char* src, size_t n)
|
|
{
|
|
size_t i = 0;
|
|
while(i++ != n && (*dst++ = *src++));
|
|
}
|
|
|
|
|
|
/*
|
|
* strncmp - compare two strings up to n characters
|
|
* @s1: first string
|
|
* @s2: second string
|
|
* @n: number of bytes to compare
|
|
*
|
|
* Taken from: https://github.com/DevSolar/pdclib/blob/master/functions/string/strncmp.c
|
|
*
|
|
* Return:
|
|
* $0 - @s1 and @s2 are equal
|
|
* $<0 - @s1 is less than @s2
|
|
* $>0 - @s1 is greater than @s2
|
|
*/
|
|
int strncmp(const char* s1, const char* s2, size_t n)
|
|
{
|
|
while ( n && *s1 && ( *s1 == *s2 ) ) {
|
|
++s1;
|
|
++s2;
|
|
--n;
|
|
}
|
|
if ( n == 0 ) {
|
|
return 0;
|
|
}
|
|
else {
|
|
return ( *(unsigned char *)s1 - *(unsigned char *)s2 );
|
|
}
|
|
} |