CString、char字符串长度求法及规则
1、CString
检查字符串合法性:比如全是数字
CString.SpanIncluding("0123456789");
1、CStringW和CStringA
CStringW CW = "汉字";
CStringA CA = "汉字";
std::cout<<"sizeof(CW)="<<sizeof(CW)<<std::endl;
std::cout<<"sizeof(CA)="<<sizeof(CA)<<std::endl;
std::cout<<"CW.GetLength()="<<CW.GetLength()<<std::endl;
std::cout<<"CA.GetLength()="<<CA.GetLength()<<std::endl;
结果:
sizeof(CW)=8
sizeof(CA)=8
CW.GetLength()=2
CA.GetLength()=4
2、wchar_t和char
2.1 求长度
wchar_t wCW[] = "汉字";
char aCA[] = "汉字";
std::cout<<"sizeof(wCW)="<<sizeof(wCW)<<std::endl;
std::cout<<"sizeof(CA)="<<sizeof(CA)<<std::endl;
std::cout<<"wcslen(wCW)="<<wcslen(wCW)<<std::endl;
std::cout<<"strlen(aCA)="<<strlen(aCA)<<std::endl;
结果:
sizeof(wCW)=6
sizeof(CA)=5
wcslen(wCW)=2
strlen(aCA)=4
2.2 截取字符串
2.2.1 取后多少位
char* cStr = "我以我血见轩辕!";
char* strPos="我以我血";
int n = strlen(strPos);
char *temp = cStr+n;
cout << temp << endl;
2.2.2 取前多少位
char* cStr = "我以我血见轩辕!";
char* strPos="见轩辕";
char result[13]; // 创建一个字符数组来存储前四个字符,加1是为了存储字符串结束符'\0'
strncpy(result, cStr, strlen(strPos)); // 复制前12个字节
result[12] = '\0'; // 添加字符串结束符
printf("前四个字符: %s\n", result);