二维码 短网址 cnBeta

C++截取英文和汉字(单双字节)混合字符串

在C++里截取字符串可以使用CString.Mid(),可是这个函数只能按英文(单字节)来截取,

如果是汉字可能就要计算好字符个数,如果是汉字和英文混合,那就没辙了。

可是恰好我需要这样一个函数,于是就自己修改了一个。

#include <vector>
 1 int is_zh_ch(char p)
 2 {
 3 
 4     /*汉字的两个字节的最高为都为1,这里采用判断最高位的方法
 5     将p字节进行移位运算,右移8位,这样,如果移位后是0,
 6     则说明原来的字节最高位为0,不是1那么也就不是汉字的一个字节
 7     */
 8     if(~(p >> 8) == 0)
 9     {
10         return 1;//代表不是汉字
11     }
12 
13     return -1;
14 }
15 
16 CString sub(CString str,int start,int count)
17 {
18 
19     if(typeid(str)==typeid(CString) && str.GetLength()>0)
20     {
21         int len=str.GetLength();
22 
23         CString tmp="";
24 
25         //先把str里的汉字和英文分开
26         vector<CString> dump;
27         int i=0;
28         while(i<len)
29         {
30             if (is_zh_ch(str.GetAt(i))==1)
31             {
32                 dump.push_back(str.Mid(i,2));
33                 i=i+2;
34             }
35             else
36             {
37                 dump.push_back(str.Mid(i,1));
38                 i=i+1;
39             }
40         }
41         int residue_length=dump.size()-(start+1);
42         count=(count>0&&count<residue_length)?count:residue_length; //count默认为从start到结束的长度
43         if(start<0||start>start+count){
44             printf("start is wrong");
45         }
46         //直接从dump里取即可
47         for(i=start; i<start+count; i++)
48         {
49             tmp+=dump[i];
50         }
51 
52         return tmp;
53     }
54     else
55     {
56         printf("str is not string\n");
57         return "";
58 
59     }
60 }

 

参考:http://www.cnblogs.com/xdao/archive/2013/04/11/3015490.html

posted @ 2016-12-16 19:41  何苦而乐  阅读(354)  评论(0编辑  收藏  举报
返回顶部