VC带GBK编码的字符串拷贝函数,防止截取半个中文字符的情况发生

GBK字符串拷贝
本文介绍了一个用于处理GBK编码字符串的自定义拷贝函数strncpy2,并通过示例演示了如何避免在拷贝过程中截断中文字符的问题。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值