错误 C2137:C++ 中的空字符常量

error C2137 : Empty character constant in c++

这是代码:

void SomeClass::SomeFunctionToCorrectName(CString &strName)
{
        
    //  Only alphabets (Aa-Zz), numbers(0-9), "_" (underscore) and "-" (hyphen) are allowed. 
                
        for(int nIndex = 0; nIndex < strName.GetLength(); nIndex++)
        {
            TCHAR currentChar = strName.GetAt(nIndex);
            
            if((currentChar >= _T('a') && currentChar <= _T('z')) ||
                (currentChar >= _T('A') && currentChar <= _T('Z')) ||
                (currentChar >= _T('0') && currentChar <= _T('9')) ||
                currentChar == _T('-') || currentChar == _T('_'))
            {
                continue;
            }
            strName.Replace(currentChar,_T(''));    
        }
}

此方法会删除 strName 中的任何额外内容,并且只允许使用字母 (Aa-Zz)、数字 (0-9)、“_”(下划线)和“-”(连字符)。 if 案例将检查那些允许的条件。 如果它不在允许的条件下,它将删除它。

For Eg desired i/p :"Hel*lo*World" and desired o/p : "HelloWorld"

但是下面给我的错误如下:

error C2137: empty character constant

I can fix this error by using any of the three methods:
1. using '[=12=]'
2. using ' ' (space in between ' ')
3. using ""[0]

但这会在替换时引入 space。

Input :Hel*lo*World
Output :Hel lo World
Desired Output :HelloWorld

谁能建议我怎样才能得到想要的结果?

如果你想删除一个特定的字符,那么Replace不是正确的使用方法。正如您所注意到的,没有任何合理的字符可以替换为。

您可以像这样使用 Remove

strName.Remove(currentChar);

试试这个:

#include <string>
#include <iostream>

std::string someFunctionToCorrectName(std::string &strName)
{
    for(int nIndex = 0; nIndex < strName.size(); nIndex++)
    {
            char currentChar = strName[nIndex];
            if (
                (currentChar >= 'a' && currentChar <= 'z') ||
                (currentChar >= 'A' && currentChar <= 'Z') ||
                (currentChar >= '0' && currentChar <= '9') ||
                currentChar == '-' || currentChar == '_')
            {
                continue;
            }
            strName.erase(nIndex, 1);    
    }
    return strName;
}

int main() {
    std::string str("Hel*lo*World");
    std::cout << someFunctionToCorrectName(str) << "\n"; //==> HelloWorld
    return 0;
}