strcpy:
函数原型:
char *strcpy(char *dest, const char* src) ;------将src中包括null的字符串复制到dest所指向的内存中,返回dest指针
所需头文件#include <string>
实现方式:
char *strcpy(char *dest, const char* src)
{
assert(dest != NULL && src != NULL) ;
char *str = dest ;
while((*str++ = *src++) != '\0') ;
return dest ;
}
例1:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
char dest[] = "hello, i am!" ;
char source[] = "abc" ;
strcpy(dest, source) ;
printf("%s\n", dest) ;
for (int i = 0; i < sizeof(dest) ; ++i)
cout <<dest[i] ;
system("pause") ;
return 0 ;
}
输出结果:
可以看出他是把'\0'也复制过去了
strncpy:
函数原型:char * strncpy(char *dest, char *src, size_t num);
功能:会将src中的num个字符复制到dest,如果中途要到'\0'字符,则会填充'\0'字符
如:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
char dest[] = "hello, i am!" ;
char source[] = "a\0def" ;
strncpy(dest, source, 5) ;
printf("%s\n", dest) ;
for (int i = 0; i < sizeof(dest) ; ++i)
cout <<dest[i] ;
system("pause") ;
return 0 ;
}
其运行结果如下:
例:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
char* source="how are you ?";
char dest[20]="ABCDEFGHIJKLMNOPQRS";
strcpy(dest,source); //
strncpy(dest, source, sizeof(dest));//
printf("%s\n", dest) ;
for (int i = 0; i < sizeof(dest) ; ++i)
cout <<dest[i] ;
system("pause") ;
return 0 ;
}
当语句是strcpy(dest, source) ;时输出是:
看来他是不填充'\0'的
当语句是strncpy(dest, source, sizeof(dest)) ;输出:
此时会填充'\0'
例:
#include <string>
#include <iostream>
using namespace std ;
int main()
{
char* source="how are you ?";
char dest[10];
//strcpy(dest,source); //此时会内存溢出
strncpy(dest, source, sizeof(dest));//此时可以但目标字符串没有'\0'字符,需要我们自己加上'\0'字符
dest[sizeof(dest) - 1] = '\0' ;
printf("%s\n", dest) ;
for (int i = 0; i < sizeof(dest) ; ++i)
cout <<dest[i] ;
system("pause") ;
return 0 ;
}
对于src大于dest时需要手动加上'\0'结束符否则出现:
加上就行了,但会漏掉一些字符,所以适合str小于dest的情况.