字符串函数使用与剖析——长度受限的字符串函数

长度受限的字符串函数

一、strncpy函数
char* strncpy(char *dest,const char *src,size_t num);
功能:拷贝num个字符从源字符串到目标空间
规定:

  • 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后面追加0,直到num个。
    1、strncpy函数模拟实现
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
#include <assert.h>
//strncpy函数模拟实现
void my_strncpy(char *dest, const char* src, int num){
	assert(dest!=NULL);//判断是否为空指针,如果为空指针则打印错误信息
	assert(src != NULL);
	int i = 1;
	for (i = 1; i <= num; i++){//判断src的长度是否小于需要拷贝的字符长度
		if (*src == '\0'){//当src的长度小于需要拷贝的字符长度,则在后面补'\0'
			*dest = '\0';
			dest++;
		}
		else{
			*dest = *src;//把src的字符复制到目标空间
			dest++;
			src++;
		}
	}
}
int main(){
	char arr1[NUM] = "abcdef";
	char arr2[] = "weqtqwe";
	 my_strncpy(arr1, arr2,4);
	printf("%s", arr1);
	system("pause");
	return 0;
}

2、库函数实现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 num);
功能:将源字符串中的前num个字符追加到目标空间去,最后补上一个’\0’
规定:在源字符串长度小于num时,把源字符串追加到目标空间后补个’\0’即可。
1、strncat函数实现

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
#include <assert.h>
//strncat函数模拟实现
void my_strncat(char* dest, const char *src, int num){
	assert(dest);//判断是否为空指针
	assert(src);
	while (*dest != '\0'){//挪到目标空间的最后面
		dest++;
	}
	while (num && (*src != '\0')){//判断源字符串的长度是否小于追加字符长度
		*dest = *src;
		dest++;
		src++;
		num--;
	}
	if (*src == '\0'){//当源字符串长度小于追加字符长度,追加'\0',然后结束strncat函数
		*dest = *src;
	}
}
int main(){
	char arr1[NUM] = "abcdef";
	char arr2[] = "weqtqwe";
	 my_strncat(arr1, arr2,4);
	printf("%s", arr1);
	system("pause");
	return 0;
}

2、库函数实现方法

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函数
strncmp(const char* str1,const char* str2,int num);
功能:比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完。
规定:

  • 前num个字符相等就返回0
  • str1比str2字符大则返回大于0的数
  • str1比str2字符小则返回小于0的数
  • 比较的不是字符串长度!而是字符的ascii码值。
    1、strncmp函数模拟实现
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
#include <assert.h>
//strncmp函数模拟实现
int my_strncmp(const char* str1, const char *str2, int num){
	assert(str1);
	assert(str2);
	while (num && (*str1 == *str2)){//比较源字符串和目标字符串前num个字符
		num--;
		str1++;
		str2++;
	}
	if (num == 0){//如果前num字符完全相等,则返回0
		return 0;
	}
	else {
		return *str1 - *str2;//如果不相等,则返回第一个字符减去第二个字符的值
	}
}
int main(){
	char arr1[] = "abcdef";
	char arr2[] = "abcaqwe";
	int ret =  my_strncmp(arr1, arr2,4);
	printf("%d", ret);
	system("pause");
	return 0;
}

2、库函数实现方式

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* str1,const char* str2);
功能:找子串,如果找到则把子串开始的第一个字符的地址传回主函数。
1、strstr函数模拟实现

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
#include <assert.h>
//strstr函数模拟实现
char* my_strstr(const char* p1, const char* p2){
	assert(p1);//判断是否为空指针
	assert(p2);
	//s1、s2是用来移动比较字符的
	char *s1 =(char*) p1;//把p1强制转换为char*类型,不然因为p1是const,程序会出现警告
	char *s2 = (char*)p2;//p2同理
	char *cur = p1;//cur是用来记录字符串匹配的起点
	while (*cur){
		s1 = cur;
		s2 = p2;
		while (*s1&&*s2 && (*s1 == *s2)){
			s1++;
			s2++;
		}
		if ((*s1 == '\0')&&*s2){//目的字符串找到了最后一个字符,但是s2没有完全匹配,则无该字串
			printf("没有匹配的子串");
			return NULL;
		}
		else if (*s2 == '\0'){//在目标字符串中找到了源字符串
			return cur;
		}
		else{
			cur++;//没有匹配上,cur往后 走一个字符,重新开始匹配
		}
	}
}
int main(){
	char arr1[] = "abbbcdef";
	char arr2[] = "bbc";
	char* ret =  my_strstr(arr1, arr2);
	printf("%s", ret);
	system("pause");
	return 0;
}

2、库函数源码实现过程

char * __cdecl strstr (
        const char * str1,
        const char * str2
        )
{
        char *cp = (char *) str1;
        char *s1, *s2;

        if ( !*str2 )
            return((char *)str1);

        while (*cp)
        {
                s1 = cp;
                s2 = (char *) str2;

                while ( *s1 && *s2 && !(*s1-*s2) )
                        s1++, s2++;

                if (!*s2)
                        return(cp);

                cp++;
        }

        return(NULL);

}

五、strtok函数*(了解如何使用即可)*
char * strtok(char* str,const char* sep);
sep参数是个字符串,定义了用作分隔符的字符串集合
规定:

  • 第一个参数指定一个字符串,它包括了0个或者多个由sep字符串中的一个或者多个分隔符分割的标记。
  • strtok函数找到str的下一个标记,并将其用\0结尾,返回一个指向这个标记的指针。(注:strtok函数会改变被操作的字符串,所以在使用strtok函数切分的字符串一般都是临时拷贝的内容并且可修改。
  • strtok函数的第一个参数不为NULL,函数将找到str中的第一个标记,strtok函数将保存它在字符串中的位置。
  • strtok函数的第一个参数为NULL,函数将在同一字符串中被保存的位置开始,查找下一标记。
  • 如果字符串中不存在更多的标记,则返回NULL指针。

1、库函数源码实现过程

har * __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);
功能:返回错误码,所对应的错误信息。

以下来自linux 2.4.20-18的内核代码中的/usr/include/asm/errno.h
#ifndef _I386_ERRNO_H
#define _I386_ERRNO_H
#define EPERM 1 /* Operation not permitted */
#define ENOENT 2 /* No such file or directory */
#define ESRCH 3 /* No such process */
#define EINTR 4 /* Interrupted system call */
#define EIO 5 /* I/O error */
#define ENXIO 6 /* No such device or address */
#define E2BIG 7 /* Arg list too long */
#define ENOEXEC 8 /* Exec format error */
#define EBADF 9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */
#define EDEADLOCK EDEADLK
#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define EREMOTEIO 121 /* Remote I/O error */
#define EDQUOT 122 /* Quota exceeded */
#define ENOMEDIUM 123 /* No medium found */
#define EMEDIUMTYPE 124 /* Wrong medium type */
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值