2010-06-24 94 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函數相同的結果。