欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一起來了解c語言的str函數(shù)

 更新時間:2022年02月14日 14:31:33   作者:roseisbule  
這篇文章主要為大家詳細(xì)介紹了c語言的str函數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

strlen:

用于求字符串長度,從首字符開始,到'\0'結(jié)束,'\0'不計入總長度。

函數(shù)實現(xiàn):

size_t my_strlen(const char* ptr)
{
	assert(ptr);
	const char* ptx = ptr;
	while (*(++ptx));
	return (size_t)(ptx - ptr);
}

strcmp:

用于比較兩個字符串大小,注意大小并不是指字符串長度,而是從第一個字符開始比較,比較字符的大小。該函數(shù)返回的是一個int值,不同編譯器,返回的值是不一樣。但是正負(fù)是一致的,當(dāng)?shù)谝粋€大于第二個,返回正值,小于則返回負(fù)值,相等返回0。

函數(shù)實現(xiàn):

int my_strcmp(const char* str1,const char* str2)
{
	assert(str1 && str2);
	while((!(*str1 - *str2)) && ((*(str1++)) * (*(str2++))));
	return (int)(*str1 - *str2);
}

strcpy:

用于復(fù)制字符串。

函數(shù)實現(xiàn):

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

strcat:

用于在目標(biāo)字符串末尾追加一個字符串。

函數(shù)實現(xiàn):

char* my_strcat(char* a, const char* b)
{
	assert(a && b);
	char* tmp = a;
	while (*(++a));
	while (*(a++) = *(b++));
	*a = '\0';
	return tmp;
}

strstr:

用于在一個字符串內(nèi)尋找另一個字符串。這于KMP算法有關(guān)。

函數(shù)實現(xiàn):

const char* my_strstr(const char* a, const char* b)//a為長字符串 b為短字符串
{
	char* cp = (char*)a;
	char* s1;
	char* s2;
	if (!*b)
		return a;
	while (*cp)
	{
		s1 = cp;
		s2 = (char*)b;
		while (*s1 && *s2 && !(*s1 - *s2))
		{
			s1++;
			s2++;
		}
		if (!*s2)
			return cp;
		cp++;
	}
	return NULL;
}

atoi:

這個函數(shù)很有意思,它會把字符串的數(shù)字串轉(zhuǎn)化為int值。

函數(shù)實現(xiàn):

int my_atoi(const char* str)
{
	assert(str);
	int num = 0;
	int result = 0;
	const char* tmp = str;
	while (*str && *str != '.')
	{
		num++;
		str++;
	}
	while (num--)
	{
		result += (*tmp - '0') * (int)pow(10, num);
		tmp++;
	}
	return result;
}

strncpy,strncmpstrncat

三個函數(shù)都是限制了字符個數(shù),功能是一樣的。

函數(shù)實現(xiàn):

char* my_strncpy(char* dest, const char* sou, size_t num)
{
	assert(dest && sou);
	char* tmp = dest;
	while ((num--) && (*(dest++) = *(sou++)));
	return tmp;
}
char* my_strncat(char* a, const char* b, int n) 
{
	assert(a && b);
	char* tmp = a;
	while (*(++a));
	while ((n--) && (*(a++) = *(b++)));
	*a = '\0';
	return tmp;
}
int my_strncmp(const char* str1, const char* str2,int n)
{
	assert(str1 && str2);
	while ((!(*str1 - *str2)) && ((*(str1++)) * (*(str2++))) && (n--));
	return (int)(*str1 - *str2);
}

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容! 

相關(guān)文章

最新評論