2010-06-24 95 views
1

我有以下代码。Unicode支持isdigit和isspace功能

// mfc.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include "mfc.h" 

#ifdef _DEBUG 
#define new DEBUG_NEW 
#endif 

#include <cctype> 
#include <string> 
#include <sstream> 
#include <tchar.h> 
#include <iostream> 
#include <Strsafe.h> 
#include <algorithm> 
#include <cmath> 
#include <limits> 
#include <functional> 
#include <cassert> 

std::wstring toStringWithoutNumerical(const std::wstring& str) { 
    std::wstring result; 

    bool alreadyAppendSpace = false; 
    for (int i = 0, length = str.length(); i < length; i++) { 
     const TCHAR c = str.at(i); 
     if (isdigit(c)) { 
      continue; 
     } 
     if (isspace(c)) { 
      if (false == alreadyAppendSpace) { 
       result.append(1, c); 
       alreadyAppendSpace = true; 
      } 
      continue; 
     } 
     result.append(1, c); 
     alreadyAppendSpace = false; 
    } 

    return result; 
} 


// The one and only application object 

CWinApp theApp; 

using namespace std; 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) 
{ 
    int nRetCode = 0; 

    // initialize MFC and print and error on failure 
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) 
    { 
     // TODO: change error code to suit your needs 
     _tprintf(_T("Fatal Error: MFC initialization failed\n")); 
     nRetCode = 1; 
    } 
    else 
    { 
     // TODO: code your application's behavior here. 
    } 

    std::wstring me = toStringWithoutNumerical(_T("My Leg 1 Long")); 
    AfxMessageBox(me.c_str()); 

    // Crash! 
    std::wstring he = toStringWithoutNumerical(L"我的脚1盘"); 
    AfxMessageBox(he.c_str()); 

    return nRetCode; 
} 

对于第一个消息框,

我的腿长

将被显示。

对于第二个消息框,碰撞会发生,与断言失败在isctype.c

_ASSERTE((unsigned)(c + 1) <= 256); 

我怎样才能得到一个标准功能(ISDIGIT,isspace为...),以支持Unicode出256范围?

回答

0

还有一个C++模板的isspaceisdigit区域识别的版本,位于<locale>头,如果你想要去的多。

0

处理Unicode字符的正确方法非常复杂。但是,如果你只是想检查几个字符类别,你通常可以做到没有太多的麻烦。

POSIX(Unix)中的Unicode接口是u_isXYZ,比如u_isspace()。

http://icu-project.org/apiref/icu4c/index.html

#include <unicode/uchar.h> 

... 
if(u_isspace(c)) 
{ 
    ... // this is a space character 
} 
... 

从我所看到的ICU库是MS-Windows下可用,所以你应该能够使用它。请记住,MS-Windows下的wchar_t只有16位,因此您必须自己处理代理(0xD800和0xDFFF之间的值表示0x10000和0x10FFFF之间的字符 - 虽然这些操作的用处不大不涉及亚洲语言)。

默认的iswspace()是语言环境绑定,并且明确不会返回与正确的Unicode函数相同的结果。