C++中汉字字符串的截取
g++ main.cpp 进行编译。
为了解决限定长度的赋值, 如果出现半个中文,则采取截断措施,解决中文乱码问题。
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; #define MAX_SIZE 32 int chinese_split(std::string str,int index) { if(index > str.size()) return 0; if((str[index]&0x80) == 0x80){ if((str[index-1]& 0x80) == 0){ return 1; }else{ int n = 1; while(((str[index-n] &0x80) == 0x80 )&&((str[index-n] &0x40) == 0)){ ++n; } return n; } }else{ return 0; } } void my_strcpy(char *dst, const char *src , int index , int count = 10){ if(strlen(src) > MAX_SIZE && index >4){ int n = chinese_split(src,index); cout<<n<<endl; strncpy(dst,src,index-n); }else{ strcpy(dst,src); } } int main(){ char a[] = "方案是ie以写文件的形式写下来,wifi热点模块在启动时会以读文件形式读取配置文件并且配置"; char b[MAX_SIZE]; cout<<"-----------"<<endl; for(int i=20;i<32; i++ ){ memset(b,0,MAX_SIZE); my_strcpy(b,a,i); cout<< b<<endl; } return 0; }
代码中,限定长度是32,大于32,拷贝长度为 i.
无论如何,这种方法解决了问题。哈哈!