C language - simulation implementation of some string functions

This article is a simulation implementation of some string functions. For an in-depth understanding of string functions, you can browse C language - character functions and string functions_study notes

Simulate implementation of strlen

size_t my_strlen(const char* ptr)
{
    
    
	assert(ptr);
	char* start = ptr;
	while (*ptr != '\0')
	{
    
    
		ptr++;
	}
	return (size_t)(ptr - start);
}

Simulate implementation of strcpy

char* my_strcpy(char* dest, const char* src)
{
    
    
	assert(dest && src);
	char* ptr = dest;
	while (*dest++ = *src++)
	{
    
    
		;
	}
	return ptr;
}

Simulate the implementation of strcat

char* my_strcat(char* dest, const char* src)
{
    
    
	assert(dest && src);
	char* ptr = dest;
	while (*dest != '\0')
	{
    
    
		dest++;
	}
	while (*dest++ = *src++)
	{
    
    
		;
	}

	return ptr;
}

Simulate implementation of strcmp

int my_strcmp(const char* str1, const char* str2)
{
    
    
	assert(str1 && str2);
	while (*str1 == *str2)
	{
    
    
		if (*str1 == '\0')
		{
    
    
			return 0;
		}
		str1++;
		str2++;
	}
	return *str1 - *str2;
}

Simulate the implementation of strstr

const char* my_strstr(const char* s1, const char* s2)
{
    
    
    assert(s1 && s2);
    char* cp = s1;
    char* p1 = NULL;
    char* p2 = NULL;
    if (*s2 == '\0')
    {
    
    
        return s1;
    }
    while (*cp)
    {
    
    
        p1 = cp;
        char* p2 = s2;

        while (*p1 == *p2 && *p1 && *p2)
        {
    
    
            p1++;
            p2++;
            
        }
        if (*p2 == '\0')
        {
    
    
            return cp;
        }
        cp++;

    }
    return NULL;
    
}

Simulate implementation of strncpy

char* my_strncpy(char* s1, const char* s2, size_t num)
{
    
    
	assert(s2);
	char* ret = s1;
	while (*s2 && num)
	{
    
    
		*s1 = *s2;
		num--;
		s1++;
		s2++;
	}
	return ret;
}

Simulate implementation of strncat

char* my_strncat( char* s1, const char* s2,size_t num)
{
    
    
	assert(s2);
	char* ret = s1;
	while (*s1)
	{
    
    
		s1++;
	}
	while (*s2 && num)
	{
    
    
		*s1 = *s2;
		s1++;
		s2++;
		num--;
	}
	return ret;
}

Simulate implementation of strncmp

int my_strncmp(const char *s1, const char *s2, size_t n) 
{
    
    
    while(n--) 
    {
    
    
        if(*s1 != *s2)
            return *s1 - *s2;
        else if(*s1 == '\0')
            return 0;
        s1++;
        s2++;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/yjagks/article/details/132795826