字符串处理函数

// 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值