检查Cstring是否只包含中文字符

Check whether a Cstring contains only Chinese characters

本文关键字:中文 字符 包含 Cstring 是否 检查      更新时间:2023-10-16

我正在检查CString变量是否只包含]个中文字符。中文字符的Unicode范围为4E00 - 9FFF。

我正在做如下的事情:

CString str;
char ch;
GetDlgItemText( IDC_EDIT1, str );
for(int i=0;i<str.GetLength();i++) {
  ch=str[i];
  if(ch>='u4E00'&&ch<='u9FFF') {
  //even if input chinese character here 'if' evaluates to false
    SetDlgItemText( IDC_RICHEDIT21, str );
    SendDlgItemMessage( IDC_RICHEDIT21, EM_REPLACESEL, TRUE, (LPARAM)(LPCTSTR)str);
  } else
    break;

但是如果我做了

if(ch=='u4E00')

并输入符号u4E00,然后工作正常。

所以我的问题是,如何找到一个字符是否在一个特定的Unicode范围内?

还有一件事:如果我使用if(ch=='u4e00'),那么它返回真,但如果我使用if(ch<='u4e00'),它返回假。我不理解这种行为!

我的代码是
CString str;
wchar_t ch;
GetDlgItemText( IDC_EDIT1, str );
for(int i=0;i<str.GetLength();i++) {
  ch=str[i];
  if(ch<='u4e01') {
    //returns false,  but returns true if(ch=='u4e01')
    SetDlgItemText( IDC_RICHEDIT21, str );
    SendDlgItemMessage( IDC_RICHEDIT21, EM_REPLACESEL, TRUE, (LPARAM)(LPCTSTR)str);
  else
    break;
}

中文字符范围:

  • u +3400 - u + 4db5
  • u + 4e00 - u + 62ff
  • u +6300 - u + 77ff
  • u +7800 - u + 8cff
  • u + 8d00 - u + 9fcc
  • u +20000 - u + 215ff
  • u +21600 - u + 230ff
  • u +23100 - u + 245ff
  • u +24600 - u + 260ff
  • u +26100 - u + 275ff
  • u +27600 - u + 290ff
  • u +29100 - u + 2a6df
  • u + 2a700 - u + 2b734
  • u + 2b740 - u + 2b81d

你必须检查所有这些范围是否完整和彻底。

"char"类型的取值范围是-128~127或0~255,具体取决于您的编译器。您应该使用"wchar_t"或"unsigned short"使其范围从0到65535,否则该变量无法表示unicode字符。

顺便说一句,你不应该把SetDlgItemText和SendDlgItemMessage放在if块中。在for之前定义变量"i",并检查i的值是否等于str.Length()。

我得到了答案。可作如下比较:

CString str;
wchar_t ch;
GetDlgItemText( IDC_EDIT1, str );
for(int i=0;i<str.GetLength();i++) {
  ch=str[i];
  if((unsigned int)ch>=0x4E00u&&(unsigned int)ch<=ox9FFFu) {
    SetDlgItemText( IDC_RICHEDIT21, str);
    SendDlgItemMessage( IDC_RICHEDIT21, EM_REPLACESEL, TRUE, (LPARAM)(LPCTSTR)str);
  } else
    break;