从字符串中替换字符

时间:2014-06-30 14:10:06

标签: c++ character-encoding mfc

我的代码如下(缩小):

CComVariant * input 是输入参数

    CString cstrPath(input ->bstrVal);    
    const CHAR cInvalidChars[] = {"/*&#^°\"§$[]?´`\';|\0"};
    for (unsigned int i = 0; i < strlen(cInvalidChars); i++)
    {
       cstrPath.Replace(cInvalidChars[i],_T(''));
    }

调试时,cstrPath的值为L“§”,cInvalidChars [7]的值为-89'§'

之前我曾尝试使用.Remove(),但问题仍然存在:当涉及到§或'时,代码表似乎不匹配,并且char无法正确识别且不会被删除。使用TCHAR数组进行invalidChars会导致甚至出现不同的问题('§' - &gt;'ㅄ')。 问题似乎是我没有使用正确的代码表,但到目前为止我尝试的所有内容都没有取得任何成功。 我想成功替换/删除任何出现的'§'..

我也看过几个“从字符串中删除字符”-Posts但我找不到任何帮助我的东西。

可执行代码:

CComVariant* pccovaValue = new CComVariant();
pccovaValue->bstrVal = L"§§";

const CHAR cInvalidChars[] = {"§"};
CString cstrPath(pccovaValue->bstrVal);

for (unsigned int i = 0; i < strlen(cInvalidChars); i++)
{
    cstrPath.Remove(cInvalidChars[i]);
}

cstrPath = cstrPath;

进入 cstrPath = cstrPath;

1 个答案:

答案 0 :(得分:1)

根据评论,您正在混合使用Unicode和ANSI编码。您的应用程序似乎是针对Unicode的,这很好。你应该完全停止使用ANSI。

像这样声明cInvalidChars

CString cInvalidChars = L"/*&#^°\"§$[]?´`\';|";

使用L前缀意味着字符串文字是宽字符UTF-16文字。

然后你的循环看起来像这样:

for (int i = 0; i < cInvalidChars.GetLength(); i++)
    cstrPath.Remove(cInvalidChars[i]);
相关问题