0
点赞
收藏
分享

微信扫一扫

『C语言』字符串函数「超详细」

🌴『C语言』字符串de函数 🌴

🚩write in front🚩

🎉前言🎉 

🎄strlen() - 计算字符串长度🎄

🎄strlen()函数代码示例🎄

🎄创建自定义函数实现strlen()的功能🎄

🎄strcpy() - 复制字符串🎄

🎄strcpy()函数代码示例🎄

🎄创建自定义函数实现strcpy()的功能🎄

🎄strcat() - 连接字符串🎄

🎄strcat()函数代码示例🎄 

🎄创建自定义函数实现strcat()的功能🎄

🎄strcmp() - 比较字符串🎄

🎄strcmp()函数代码示例🎄 

🎄创建自定义函数实现strcmp()🎄   

🔧 限制 🔧

🎋strncpy() - 复制字符串(受长度限制)🎋

🎋strncpy()函数代码示例🎋

🎋strncpy()源程序实现🎋 

🎋strncat() - 连接字符串(受长度限制)🎋

🎋strncat()函数代码示例🎋

🎋strncat()源程序实现🎋 

🎋strncmp() - 比较字符串(受长度限制)🎋 

🎋strncmp()函数代码示例🎋  

🎋strncat()源程序实现🎋

🎍strstr() - 在一个字符串中查找另外一个字符串🎍

🎍strstr()函数代码示例🎍

🎍创建自定义函数实现strstr()🎍

🎍strtok() - 切割字符串🎍

🎍strtok()函数代码示例🎍

🎍strtok()源程序实现🎍

🎍strerror() - 返回错误码🎍 

🎍strerror()函数代码示例🎍

🎍strerror()源程序实现🎍

✨最后✨

🎉前言🎉 

记得三连(o゚v゚)ノ


🎄strlen() - 计算字符串长度🎄

size_t strlen ( const char * str );

🎄strlen()函数代码示例🎄

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>

int main(void)
{
	char str[20] = {"44778899"};

	int len = strlen(str);
	printf("%s 的长度是 %d\n", str, len);

	return(0);
}
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>

int main(void)
{
	char str[] = {'a','b','c'};

	int len = strlen(str);
	printf("%s 的长度是 %d\n", str, len);

	return(0);
}

🎄创建自定义函数实现strlen()的功能🎄

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>//assert的头文件
int My_strlen(const char *arr)
{
	unsigned int Count = 0;//统计字符不可能是为负数的!
    assert(arr!=NULL);//这里加入到断言就能确保我们输入字符串的时候不会是空指针
	while (*arr != '\0')
	{
		Count++;
		*arr++;
	}
	return Count;//返回计算机长度
}
int main(void)
{
	char enter[20] = { 0 };
	printf("请输入字符串->:");
	scanf("%s", &enter);
	int ret = My_strlen(enter);
	printf("The total number of input strings:%d\n",ret);
	return 0;
}

🎄strcpy() - 复制字符串🎄

char *strcpy(char *dest, const char *src)

🎄strcpy()函数代码示例🎄

#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="C语言";
  char str2[40];
  char str3[40];
  strcpy (str2,str1);
  strcpy (str3,"C++语言");
  printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
  return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>

int main()
{
	char str1[] = { 'a', 'b', 'c' };
	char str2[40];
	strcpy(str2, str1);
	printf("%s", str2);
	return 0;
}

  

🎄创建自定义函数实现strcpy()的功能🎄

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <assert.h>
void My_strcpy(char *dest, const char *src)
{
	assert(dest != NULL);
	assert(src != NULL);
	while (*src != '\0')
	{
		*dest = *src;//进行赋值
		*src++;
		*dest++;//指向下一个字符
	}
}
int main(void)
{
	char *p = "C语言";
	char str[20] = { 0 };
	My_strcpy(str, p);
	printf("str = %s\n",str);
	return 0;
}

🎄strcat() - 连接字符串🎄

char *strcat(char *dest, const char *src)
char arr[20] = "Cyuyan"
strcat(arr,arr);
printf("%s\n",arr);

🎄strcat()函数代码示例🎄 

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main(void)
{
	char arr1[20] = "hello C";
	char arr2[20] = "yuyan";
	strcat(arr1, arr2);
	printf("arr1 = %s\n", arr1);
	return 0;
}

🎄创建自定义函数实现strcat()的功能🎄

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
char *My_strcat(char *dest, const char *src)
{
	assert(dest && src != NULL);//断言
	char *ret = dest;
	while (*dest != '\0')//'\0'的ASCLL码值就是0
	{
		dest++;
	}
    //dest指向的是'\0'
	while (*dest++ = *src++)
	{
		;
	}
    /*相当于
	while (*src != '\0')
	{
		*dest++ = *src++;
	}*/
	return ret;
}
int main(void)
{
	char arr1[20] = "hello C";
 	char arr2[20] = "yuyan";
	printf("%s\n", My_strcat(arr1, arr2));
	return 0;
}


🎄strcmp() - 比较字符串🎄

int strcmp(const char *str1, const char *str2)

🎄strcmp()函数代码示例🎄 

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main()
{
	char str1[20] = { 0 };
	char str2[20] = { 0 };
	puts("请输入第一个字符串:");
	scanf("%s", &str1);
	puts("请输入第二个字符串:");
	scanf("%s", &str2);
	puts("返回的值:");
	printf("%d",strcmp(str1, str2));
	return 0;
}

🎄创建自定义函数实现strcmp()🎄   

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
int my_strcmp(const char *str1, const char *str2)
{
	assert(str1 && str2 != NULL);
	while (*str1 == *str2)
	{
		//判断相等情况,有一个相等就代表*str2也是一样的
		if (*str1 == '\0')
		{
			return 0;
		}
		*str1++;
		*str2++;//自增比较
	}
	if (*str1 > *str2)
		return 1;//大于
	else
		return -1;//小于
	//其实还有一种更简单的方法,大于小于。
	//return *str1 - *str2;
	//这个是指针减指针的概念,前面介绍有说过!
}
int main()
{
	char str1[20] = { 0 };
	char str2[20] = { 0 };
	puts("请输入第一个字符串:");
	scanf("%s", &str1);
	puts("请输入第二个字符串:");
	scanf("%s", &str2);
	int ret = my_strcmp(str1, str2);
	printf("返回的值:%d\n",ret);
	return 0;
}


🔧 限制 🔧


🎋strncpy() - 复制字符串(受长度限制)🎋

char *strncpy(char *dest, const char *src, size_t n)

🎋strncpy()函数代码示例🎋

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main(void)
{
	char str1[20] = "helloC";
	char str2[] = "HELLO";
	printf("字节=%d\n", sizeof(str2));
	printf("str = %s\n",strncpy(str1, str2, sizeof(str2)));
	return 0;
}

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main(void)
{
	char str1[20] = "helloC";
	char str2[] = "HELLO";
	printf("字节=%d\n", sizeof(char));
	printf("str = %s\n", strncpy(str1, str2, sizeof(char)));
	return 0;
}

🎋strncpy()源程序实现🎋 

char * __cdecl strncpy (
        char * dest,
        const char * source,
        size_t count
        )
{
        char *start = dest;

        while (count && (*dest++ = *source++))    /* copy string */
                count--;

        if (count)                              /* pad out with zeroes */
                while (--count)
                        *dest++ = '\0';

        return(start);
}

🎋strncat() - 连接字符串(受长度限制)🎋

char *strncat(char *dest, const char *src, size_t n)

🎋strncat()函数代码示例🎋

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main(void)
{
	char str1[20];
	char str2[20];
	strcpy(str1, "Cyuyan");
	strcpy(str2, "yyds");
	printf(strncat(str1, str2, 5));//追加字符串!
	return 0;
}

printf(strncat(str1, str2, 4));

🎋strncat()源程序实现🎋 

char * __cdecl strncat (
        char * front,
        const char * back,
        size_t count
        )
{
        char *start = front;

        while (*front++)
                ;
        front--;

        while (count--)
                if (!(*front++ = *back++))
                        return(start);

        *front = '\0';
        return(start);
}

🎋strncmp() - 比较字符串(受长度限制)🎋 

int strncmp(const char *str1, const char *str2, size_t n)

🎋strncmp()函数代码示例🎋  

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main(void)
{
	char str1[20];
	char str2[20];
	strcpy(str1, "Cyuyan");
	strcpy(str2, "Cyuyanyyds");
	printf("%d", strncmp(str1, str2, 6));

	return 0;
}

🎋strncat()源程序实现🎋

int __cdecl strncmp
(
    const char *first,
    const char *last,
    size_t      count
)
{
    size_t x = 0;

    if (!count)
    {
        return 0;
    }

    /*
     * This explicit guard needed to deal correctly with boundary
     * cases: strings shorter than 4 bytes and strings longer than
     * UINT_MAX-4 bytes .
     */
    if( count >= 4 )
    {
        /* unroll by four */
        for (; x < count-4; x+=4)
        {
            first+=4;
            last +=4;

            if (*(first-4) == 0 || *(first-4) != *(last-4))
            {
                return(*(unsigned char *)(first-4) - *(unsigned char *)(last-4));
            }

            if (*(first-3) == 0 || *(first-3) != *(last-3))
            {
                return(*(unsigned char *)(first-3) - *(unsigned char *)(last-3));
            }

            if (*(first-2) == 0 || *(first-2) != *(last-2))
            {
                return(*(unsigned char *)(first-2) - *(unsigned char *)(last-2));
            }

            if (*(first-1) == 0 || *(first-1) != *(last-1))
            {
                return(*(unsigned char *)(first-1) - *(unsigned char *)(last-1));
            }
        }
    }

    /* residual loop */
    for (; x < count; x++)
    {
        if (*first == 0 || *first != *last)
        {
            return(*(unsigned char *)first - *(unsigned char *)last);
        }
        first+=1;
        last+=1;
    }

    return 0;
}

🎍strstr() - 在一个字符串中查找另外一个字符串🎍

char *strstr(const char *haystack, const char *needle)

🎍strstr()函数代码示例🎍

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main(void)
{
	char arr1[20] = "abcdef";
	char arr2[20] = "bcd";
	char ret = strstr(arr1, arr2);
	if (ret == NULL)
	{
		printf("没找到!\n");
	}
	else
	{
		printf("找到了→%s\n", ret);
	}
	return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<assert.h>
int main(void)
{
	char arr1[20] = "abcdef";
	char arr2[20] = "bf";
	char *ret = strstr(arr1, arr2);
	if (ret == NULL)
	{
		printf("没找到%s!\n",ret);
	}
	else
	{
		printf("找到了→%s\n", ret);
	}
	return 0;
}

🎍创建自定义函数实现strstr()🎍

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<assert.h>
char *my_strstr(const char *str1, const char *str2)
{
	assert(str1 && str2 != NULL);
	const char* s1 = NULL;
	const char* s2 = NULL;//在不知道赋值什么的情况下直接赋值空指针。
	if (*str2 == '\0')
		return (char*)str1;//假设str2首元素地址为空字符串直接返回str1
	while (*str1)
	{
		s1 = str1;
		s2 = str2;
		while (*s1 && *s2 != '\0' && (*s1 == *s2))
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')
		{
			return (char*)str1;//注意返回类型强制转换!
		}
		str1++;
	}
	return NULL;
}
int main(void)
{
	char arr1[20] = "abbcdef";
	char arr2[20] = "bc";
	char *ret = my_strstr(arr1, arr2);
	if (ret == NULL)
	{
		printf("没找到%s!\n",ret);
	}
	else
	{
		printf("找到了→%s\n", ret);
	}
	return 0;
}


🎍strtok() - 切割字符串🎍

char * strtok ( char * str, const char * delimiters );

🎍strtok()函数代码示例🎍

#include <stdio.h>
#include <string.h>

int main(void)
{
	char str[] = "Hello.Cyuyan.yyds";
	printf("yiduanhua|%s|dezifu\n", str);
	char * pch=strtok(str, ".");
	while (pch != NULL)
	{
		printf("%s\n", pch);
		pch = strtok(NULL, ".");
	}
	return 0;
}


🎍strtok()源程序实现🎍

/***
*strtok.c - tokenize a string with given delimiters
*
*       Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
*       defines strtok() - breaks string into series of token
*       via repeated calls.
*
*******************************************************************************/

#include <cruntime.h>
#include <string.h>
#ifdef _SECURE_VERSION
#include <internal.h>
#else  /* _SECURE_VERSION */
#include <mtdll.h>
#endif  /* _SECURE_VERSION */

/***
*char *strtok(string, control) - tokenize string with delimiter in control
*
*Purpose:
*       strtok considers the string to consist of a sequence of zero or more
*       text tokens separated by spans of one or more control chars. the first
*       call, with string specified, returns a pointer to the first char of the
*       first token, and will write a null char into string immediately
*       following the returned token. subsequent calls with zero for the first
*       argument (string) will work thru the string until no tokens remain. the
*       control string may be different from call to call. when no tokens remain
*       in string a NULL pointer is returned. remember the control chars with a
*       bit map, one bit per ascii char. the null char is always a control char.
*
*Entry:
*       char *string - string to tokenize, or NULL to get next token
*       char *control - string of characters to use as delimiters
*
*Exit:
*       returns pointer to first token in string, or if string
*       was NULL, to next token
*       returns NULL when no more tokens remain.
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/

#ifdef _SECURE_VERSION
#define _TOKEN *context
#else  /* _SECURE_VERSION */
#define _TOKEN ptd->_token
#endif  /* _SECURE_VERSION */

#ifdef _SECURE_VERSION
char * __cdecl strtok_s (
        char * string,
        const char * control,
        char ** context
        )
#else  /* _SECURE_VERSION */
char * __cdecl strtok (
        char * string,
        const char * control
        )
#endif  /* _SECURE_VERSION */
{
        unsigned char *str;
        const unsigned char *ctrl = control;

        unsigned char map[32];
        int count;

#ifdef _SECURE_VERSION

        /* validation section */
        _VALIDATE_RETURN(context != NULL, EINVAL, NULL);
        _VALIDATE_RETURN(string != NULL || *context != NULL, EINVAL, NULL);
        _VALIDATE_RETURN(control != NULL, EINVAL, NULL);

        /* no static storage is needed for the secure version */

#else  /* _SECURE_VERSION */

        _ptiddata ptd = _getptd();

#endif  /* _SECURE_VERSION */

        /* Clear control map */
        for (count = 0; count < 32; count++)
                map[count] = 0;

        /* Set bits in delimiter table */
        do {
                map[*ctrl >> 3] |= (1 << (*ctrl & 7));
        } while (*ctrl++);

        /* Initialize str */

        /* If string is NULL, set str to the saved
         * pointer (i.e., continue breaking tokens out of the string
         * from the last strtok call) */
        if (string)
                str = string;
        else
                str = _TOKEN;

        /* Find beginning of token (skip over leading delimiters). Note that
         * there is no token iff this loop sets str to point to the terminal
         * null (*str == '\0') */
        while ( (map[*str >> 3] & (1 << (*str & 7))) && *str )
                str++;

        string = str;

        /* Find the end of the token. If it is not the end of the string,
         * put a null there. */
        for ( ; *str ; str++ )
                if ( map[*str >> 3] & (1 << (*str & 7)) ) {
                        *str++ = '\0';
                        break;
                }

        /* Update nextoken (or the corresponding field in the per-thread data
         * structure */
        _TOKEN = str;

        /* Determine if a token has been found. */
        if ( string == str )
                return NULL;
        else
                return string;
}


🎍strerror() - 返回错误码🎍 

char * strerror ( int errnum );

🎍strerror()函数代码示例🎍

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
{
	FILE* Pf = fopen("test.txt", "r");//打开文件如果以读的形式存在那么这个文件就会打开失败!
	//一旦打开失败那个得到的就是NULL
	if (Pf == NULL)
	{
		printf("%s\n", strerror(errno));
		return 1;//返回main函数结束
	}
	fclose(Pf);
	Pf = NULL;
	return 0;
}

🎍strerror()源程序实现🎍

#include <cruntime.h>
#include <errmsg.h>
#include <stdlib.h>
#include <syserr.h>
#include <string.h>
#include <mtdll.h>
#include <tchar.h>
#include <malloc.h>
#include <stddef.h>
#include <dbgint.h>
#include <internal.h>

/* [NOTE: The error message buffer is shared by both strerror
   and _strerror so must be the max length of both. */
/* Max length of message = user_string(94)+system_string+2 */
#define _ERRMSGLEN_ (94+_SYS_MSGMAX+2)

#ifdef _UNICODE
#define _terrmsg    _werrmsg
#else  /* _UNICODE */
#define _terrmsg    _errmsg
#endif  /* _UNICODE */

/***
*char *strerror(errnum) - Map error number to error message string.
*
*Purpose:
*       The strerror runtime takes an error number for input and
*       returns the corresponding error message string.  This routine
*       conforms to the ANSI standard interface.
*
*Entry:
*       int errnum - Integer error number (corresponding to an errno value).
*
*Exit:
*       char * - Strerror returns a pointer to the error message string.
*       This string is internal to the strerror routine (i.e., not supplied
*       by the user).
*
*Exceptions:
*       None.
*
*******************************************************************************/

#ifdef _UNICODE
wchar_t * cdecl _wcserror(
#else  /* _UNICODE */
char * __cdecl strerror (
#endif  /* _UNICODE */
        int errnum
        )
{
        _TCHAR *errmsg;
        _ptiddata ptd = _getptd_noexit();
        if (!ptd)
                return _T("Visual C++ CRT: Not enough memory to complete call to strerror.");

        if ( (ptd->_terrmsg == NULL) && ((ptd->_terrmsg =
                        _calloc_crt(_ERRMSGLEN_, sizeof(_TCHAR)))
                        == NULL) )
                return _T("Visual C++ CRT: Not enough memory to complete call to strerror.");
        else
                errmsg = ptd->_terrmsg;

#ifdef _UNICODE
        _ERRCHECK(mbstowcs_s(NULL, errmsg, _ERRMSGLEN_, _get_sys_err_msg(errnum), _ERRMSGLEN_ - 1));
#else  /* _UNICODE */
        _ERRCHECK(strcpy_s(errmsg, _ERRMSGLEN_, _get_sys_err_msg(errnum)));
#endif  /* _UNICODE */

        return(errmsg);
}

/***
*errno_t strerror_s(buffer, sizeInTChars, errnum) - Map error number to error message string.
*
*Purpose:
*       The strerror_s runtime takes an error number for input and
*       copies the corresponding error message string in the destination
*       buffer. If the buffer is too small, the message is truncated.
*
*Entry:
*       TCHAR * buffer - Destination buffer.
*       size_t sizeInTChars - Size of the destination buffer.
*       int errnum - Integer error number (corresponding to an errno value).
*
*Exit:
*       The error code.
*
*Exceptions:
*       Input parameters are validated. Refer to the validation section of the function.
*
*******************************************************************************/

#ifdef _UNICODE
errno_t __cdecl _wcserror_s(
#else  /* _UNICODE */
errno_t __cdecl strerror_s(
#endif  /* _UNICODE */
        TCHAR* buffer,
        size_t sizeInTChars,
        int errnum
        )
{
        errno_t e = 0;

        /* validation section */
        _VALIDATE_RETURN_ERRCODE(buffer != NULL, EINVAL);
        _VALIDATE_RETURN_ERRCODE(sizeInTChars > 0, EINVAL);

        /* we use mbstowcs_s or strncpy_s because we want to truncate the error string
         * if the destination is not big enough
         */
#ifdef _UNICODE
        e = _ERRCHECK_EINVAL_ERANGE(mbstowcs_s(NULL, buffer, sizeInTChars, _get_sys_err_msg(errnum), _TRUNCATE));
        /* ignore the truncate information */
        if (e == STRUNCATE)
        {
                e = 0;
        }
#else  /* _UNICODE */
        _ERRCHECK(strncpy_s(buffer, sizeInTChars, _get_sys_err_msg(errnum), sizeInTChars - 1));
#endif  /* _UNICODE */
    return e;
}

✨最后✨

举报

相关推荐

0 条评论