Unicode支持的isdigit和isspace功能

时间:2010-06-24 08:25:39

标签: c++ unicode

我有以下代码。

// 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 ...),以支持256范围内的unicode?

3 个答案:

答案 0 :(得分:4)

答案 1 :(得分:0)

如果您想要进行多平台,还有一个C ++模板,isspaceisdigit的区域设置感知版本,位于<locale>标题中。

答案 2 :(得分: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函数相同的结果。