关于C标准库字符串操作函数(strlen,strcpy,strstr,atoi)的源码及自写

关于C标准库字符串操作函数的源码及自写

1. strlen函数(库源码)

#include
size_t strlen(const char *str) 
{
     
	const char *s;
	for (s = str; *s; ++s) //迭代器
	{
     }
	return(s - str);
}

代码解释:
迭代器:通过s来接受str中的元素,直到最后一个
返回值:因为这时两个指针同时指向字符串,str指向字符串的头,s指向字符串的尾,通过两个指针的想减即可得到字符串的长度。

自写的strlen()

int my_strlen(char * string)
{
     
	int result=0;
	while(*string != '\0')
	{
     
		result++;
		string++;
	}
	return result;
}

2.strcpy(库函数)

#include 
char* strcpy(char *to, const char *from) 
{
     
	assert(to != NULL && from != NULL);//判断两个字符串都不为空
	char *p = to;
	while ((*p++ = *from++) != '\0')//指针偏移赋值直到为空
	;
	return to;
}

自写的strcpy

void my_strcpy(char * goal,char * src)
{
     
	while(*src != '\0')
	{
     
		*goal = *src;
		goal++;
		src++;
	}
}

3.strstr(库函数)

char *strstr(const char *haystack, const char *needle)
 {
     
	// if needle is empty return the full string
	if (!*needle) return (char*) haystack;
	const char *p1;
	const char *p2;
	const char *p1_advance = haystack;
	for (p2 = &needle[1]; *p2; ++p2) 
	{
     
		p1_advance++; // advance p1_advance M-1 times
	}
	for (p1 = haystack; *p1_advance; p1_advance++) 
	{
     
		char *p1_old = (char*) p1;
		p2 = needle;
		while (*p1 && *p2 && *p1 == *p2)
		{
     
			p1++;
			p2++;
		}
		if (!*p2)
		return p1_old;
		p1 = p1_old + 1;
	}
	return NULL;
}

strstr(自写)

char *my_strstr(const char *src, const char *sub)
{
     
    const char *bp;
    const char *sp;
    if (!src || !sub)
    {
     
        return src;
    }
    /* 遍历src字符串  */
    while (*src)
    {
     
        /* 用来遍历子串 */
        bp = src;
        sp = sub;
        while ((*bp++ == *sp))
        {
     
            sp++;
        }
        //do
        if (!*sp) /*到了sub的结束位置,返回src位置   */
        {
     
            return src;
        }
        src++;
    }
    return NULL;
}

4.atoi(库函数)

int atoi(const char *str) 
{
     
	int num = 0;
	int sign = 1;
	const int len = strlen(str);
	int i = 0;
	while (str[i] == ' ' && i < len) 
		i++;
	if (str[i] == '+') 
		i++;
	if (str[i] == '-') 
	{
     
		sign = -1;
		i++;
	}
	for (; i < len; i++) 
	{
     
		if (str[i] < '0' || str[i] > '9')
		break;
		if (num > INT_MAX / 10 ||
		(num == INT_MAX / 10 &&
		(str[i] - '0') > INT_MAX % 10)) 
		{
     
			return sign == -1 ? INT_MIN : INT_MAX;
		}
		num = num * 10 + str[i] - '0';
	}
	return num * sign;
}

atoi(自写)

int my_atoi(char *str)
{
     
    int result = 0;
    int flag = 1;
    if (*str == '-')
    {
     
        flag = -1;
        str++;
    }
    while (*str != '\0')
    {
     
        if (*str >= '0' && *str <= '9')
        {
     
            result = result * 10 + ( *str - '0' );
        }
        else
        {
     
            break;
        }
 
        str++;
    }
 
    return result * flag;
}

你可能感兴趣的:(字符串,指针)