您的位置:首页 > 运维架构 > Linux

strcat strncat的使用方法

2014-06-29 01:53 295 查看
SYNOPSIS

#include <string.h>

char *strcat(char *dest, const char *src);

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

strcat 把源字符串连接到目的字符串,并且覆盖目的字符串的'\0',并且在连接后的字符串添加一个'\0',所以,要用这个函数,目的字符串剩余空间大小,必须大于源字符串有效字符个数加一

strncat 把源字符串连接到目的字符串,并且覆盖目的字符串的'\0'。不同点是,strncat最多从源字符串中取出n个字节的内容,如果源字符串的大小大于n个字节,那么strncat就截取n个字节,并且在字符串末尾添加'\0'

STRCAT(3)                                                  Linux Programmer's Manual                                                 STRCAT(3)

NAME
strcat, strncat - concatenate two strings

SYNOPSIS
#include <string.h>

char *strcat(char *dest, const char *src);

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

DESCRIPTION
The  strcat()  function appends the src string to the dest string, overwriting the null byte ('\0') at the end of dest, and then adds a
terminating null byte.  The strings may not overlap, and the dest string must have enough space for the result.

The strncat() function is similar, except that

*  it will use at most n characters from src; and

*  src does not need to be null-terminated if it contains n or more characters.

As with strcat(), the resulting string in dest is always null-terminated.

If src contains n or more characters, strncat() writes n+1 characters to dest (n from src plus the terminating null byte).   Therefore,
the size of dest must be at least strlen(dest)+n+1.

A simple implementation of strncat() might be:

char*
strncat(char *dest, const char *src, size_t n)
{
size_t dest_len = strlen(dest);
size_t i;

for (i = 0 ; i < n && src[i] != '\0' ; i++)
dest[dest_len + i] = src[i];
dest[dest_len + i] = '\0';

return dest;
}

RETURN VALUE
       The strcat() and strncat() functions return a pointer to the resulting string dest.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string linux strcat