C++中的STRCATS()VS STRNCAT()

strcat()

null

函数的作用是:将源字符串的副本附加到目标字符串的末尾。strcat()函数有两个参数: 1) 目的地 2) src 它将源字符串的副本附加到目标字符串中。 dest末尾的终止字符被src的第一个字符替换。 返回值: 函数的作用是:返回dest,即指向目标字符串的指针。

CPP

// CPP program to demonstrate
// strcat
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char dest[50] = "This is an" ;
char src[50] = " example" ;
strcat (dest, src);
cout << dest ;
return 0;
}


输出:

This is an example

strncat()

C++中的STRNCATE()函数将给定字符串的字符数附加到另一个字符串的结尾。strncat()函数将接受以下三个参数: 1) 目的地 2) Src 3) 数 这将把src string中给定数量的字符附加到dest string的末尾。 dest字符串末尾的终止字符将替换为第一个字符 src字符串的。 返回值: 函数的作用是:返回dest,即指向目标字符串的指针。

CPP

// CPP program to demonstrate
// strncat
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char dest[25] = "This is an example" ;
char src[50] = " to show working of strncat() this is not added" ;
strncat (dest, src, 29);
cout << dest ;
return 0;
}


输出:

This is an example to show working of strncat()

strncat()与strcat()有何不同?

许多程序员建议,与strcat()相比,strcat()是安全的,因为strcat()不检查复制数据的大小,并且在到达空终止符之前复制,这可能会导致缓冲区溢出,而strncat()检查复制数据的大小,并且只复制“n”字节。

CPP

// C,C++ program demonstrate difference between
// strncat() and strcat()
#include <stdio.h>
#include <string.h>
int main()
{
// Take any two strings
char src[50] = "forgeeks" ;
char dest1[50] = "geeks" ;
char dest2[50] = "geeks" ;
printf ( "Before strcat() function execution, " );
printf ( "destination string : %s" , dest1);
// Appends the entire string of src to dest1
strcat (dest1, src);
// Prints the string
printf ( "After strcat() function execution, " );
printf ( "destination string : %s" , dest1);
printf ( "Before strncat() function execution, " );
printf ( "destination string : %s" , dest2);
// Appends 3 characters from src to dest2
strncat (dest2, src, 3);
// Prints the string
printf ( "After strncat() function execution, " );
printf ( "destination string : %s" , dest2);
return 0;
}


输出:

Before strcat() function execution, destination string : geeksAfter strcat() function execution, destination string : geeksforgeeksBefore strncat() function execution, destination string : geeksAfter strncat() function execution, destination string : geeksfor

本文由 普拉纳夫 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享