// testS.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <string.h> //带GBK编码的字符串拷贝,防止截取半个中文字符的情况发生 //形参表的含义同strncpy函数 void strncpy2(char *pDst,char *pSrc,int nDstLen) { //pDst缓存足够容纳pSrc中的数据 if(strlen(pSrc)<nDstLen) { strncpy(pDst,pSrc,nDstLen); } //pDst Buffer 's size must be greater than or equal 2! if(nDstLen<2) return; memset(pDst,0,nDstLen); int nCount=0; for(int i=0;i<nDstLen;i++) { if(pSrc[i]&0x80) nCount++; } if(nCount%2==0&&pSrc[nDstLen-1]&0x80) strncpy(pDst,pSrc,nDstLen-2); else strncpy(pDst,pSrc,nDstLen-1); } //标题:演示 GBK字符串拷贝 函数的使用 //测试环境:VS2008+SP1 //Author: kagula //Date: 2010-09-11 int _tmain(int argc, _TCHAR* argv[]) { //#define DST_LEN 3 //正确结果是[a] #define DST_LEN 4 //正确结果是[a中] char pSrc[]={"a中国"}; char pDst[DST_LEN]; strncpy2(pDst,pSrc,DST_LEN); printf("pDst=[%s]/n",pDst); return 0; }