Welcome

首页 / 软件开发 / 数据结构与算法 / 提前认识软件开发(10) 字符串处理函数及异常保护

提前认识软件开发(10) 字符串处理函数及异常保护2015-01-24在软件开发项目中,经常有程序要对字符串进行操作。为此,C函数库中提供了一些用来对字符串进行处理的函数,使用起来非常的方便。但由于字符串都有长度,如果随意对不同的字符串进行连接和拷贝等操作,就可能出现意想不到的后果。

因此,在实际开发过程中,十分强调对字符串处理函数进行异常保护。本文详细介绍如何正确运用字符串处理函数进行C程序设计。

1. strcat和strncat函数

strcat函数的作用是连接两个字符数组中的字符串。在MSDN中,其定义为:

char *strcat( char *strDestination, const char *strSource );

Remarks: The strcat function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of strSource overwrites the terminating null character of strDestination. It returns the destination string (strDestination).

strcat函数将strSource字符串拼接到strDestination后面,最后的返回值是拼装完成之后的字符串strDestination。

这里有一个问题,如果字符串strSource的长度大于了strDestination数组的长度,就会出现数组越界的错误,程序就会崩溃。如下代码所示:

/****************************************************************版权所有 (C)2014, Zhou Zhaoxiong。**文件名称:StrcatTest.c*内容摘要:用于测试strcat函数*其它说明:无*当前版本:V1.0*作 者:周兆熊*完成日期:20140405**修改记录1: //修改历史记录,包括修改日期、版本号、修改人及修改内容等* 修改日期:* 版本号:* 修改人:* 修改内容:***************************************************************/#include <stdio.h>#include <string.h> typedef signed char INT8;//重定义数据类型typedef signed intINT32; //重定义数据类型 /********************************************************************** *功能描述:主函数 *输入参数:无 *输出参数:无 *返回值:无 *其它说明:无 *修改日期 版本号修改人修改内容 * ------------------------------------------------------------------------------------------ * 20140405V1.0周兆熊创建 ***********************************************************************/INT32 main(void){ INT8 szStrDestination[10] = "Hello"; INT8 szStrSource[10]= "Hello123"; //先打印源字符串和目的字符串 printf("The source string is: %s
", szStrSource); printf("The destination string is: %s
", szStrDestination);strcat(szStrDestination, szStrSource); //调用strcat函数 //打印拼装完成之后的字符串 printf("The changed destination string is: %s
", szStrDestination);return 0;}