小编use*_*457的帖子

如何在C ++中检查字符串是否具有有效的UTF-8字符?

我正在尝试使用ICU库来测试字符串是否包含无效的UTF-8字符。我创建了一个UTF-8转换器,但是没有无效数据给我一个转换错误。感谢你的帮助。

谢谢,Prashanth

int main()                                                                                        
{                                     
    string str ("AP1120 CorNet-IP v5.0 v5.0.1.22 òÀ MIB 1.5.3.50 Profile EN-C5000");
    //  string str ("example string here");
    //  string str (" ??????????"     );                  
    UErrorCode status = U_ZERO_ERROR;                   
    UConverter *cnv;            
    const char *sourceLimit;    
    const char * source = str.c_str();                  
    cnv = ucnv_open("utf-8", &status);                                                              
    assert(U_SUCCESS(status));                                                                      

    UChar *target;                                                                                  
    int sourceLength = str.length();                                                                
    int targetLimit = 2 * sourceLength;                                                             
    target = new UChar[targetLimit];                                                                

    ucnv_toUChars(cnv, target, targetLimit, source, sourceLength, &status);
    cout << u_errorName(status) << endl;
    assert(U_SUCCESS(status));                          
}       
Run Code Online (Sandbox Code Playgroud)

c++ utf-8

3
推荐指数
1
解决办法
4132
查看次数

标签 统计

c++ ×1

utf-8 ×1