// stringTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdlib.h"
#include "string.h"
void tc_strncpy(void)
{
char *str = "I love china!";
char str1[20] = "xxxxxxxxxxxxxxxxxxx";
strncpy_s(str1, 20, str, 20);
printf("strncpy_s:str1 = %s\n", str1);
char str2[20] = "xxxxxxxxxxxxxxxxxxx";
int strLen = strlen(str);
strncpy_s(str2, 20, str, strLen); //目标字符串>strLen的区间清0
printf("strncpy_s:str2 = %s\n", str2);
/*
char str3[10] = "xxxxxxxxx";
strncpy_s(str3, 10, str, strLen);
printf("strncpy_s:str3 = %s\n", str3); //输出异常
*/
/*
char str4[10] = "xxxxxxxxx";
strncpy_s(str4, 10, str, 10);
printf("strncpy_s:str4 = %s\n", str4); //输出异常
*/
char str4[10] = "xxxxxxxxx";
strncpy_s(str4, 10, str, 10 - 1); //OK,目标长度必须大于n
printf("strncpy_s:str4 = %s\n", str4);
/*
char str5[10] = "xxxxxxxxx";
strncpy_s(str5, 10 - 1, str, 10 - 1);
printf("strncpy_s:str5 = %s\n", str5); //输出异常
*/
}
void tc_strncat(void)
{
char str1[7] = "we";
char str2[] = "your";
//strncat_s(str1, 7 - 1, str2, strlen(str2)); //输出异常,输出缓存区size必须大于组合后的字符串长度
strncat_s(str1, 7, str2, strlen(str2));
printf("strncat_s:str1 = %s\n", str1);
}
void tc_strpoint(void)
{
char *str1 = "The str1 is const!";
char str2[] = "The str2 is in stack!";
char *str3 = (char *)malloc(32 * sizeof(char));
strncpy_s(str3, 32, "The str3 is in heap!", strlen("The str3 is in heap!"));
printf("str1 = 0x%x, str2 = 0x%x, str3 = 0x%x\n", str1, str2, str3);
//str1[5] = 'C'; //异常
str2[5] = 'C';
str3[5] = 'C';
}
void tc_strtok(void)
{
char str[]="ab,cd,ef";
char *ptr;
char *p;
printf("before strtok: str=%s\n",str);
printf("begin:\n");
ptr = strtok_r(str, ",", &p);
while(ptr != NULL){
printf("str=%s\n",str);
printf("ptr=%s\n",ptr);
ptr = strtok_r(NULL, ",", &p);
}
}
int main()
{
tc_strncpy();
tc_strncat();
tc_strpoint();
return 0;
}