替换字符串中的字符

Replacing chars from string

本文关键字:字符 字符串 替换      更新时间:2023-10-16

我的代码如下(简化):

CComVariant* input是一个输入参数

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

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

我以前尝试过使用。remove(),但问题仍然是一样的:当涉及到§或´时,代码表似乎不匹配,字符不能正确识别,不会被删除。对invalidChars使用TCHAR数组会导致不同的问题('§' -> 'ㅄ')。问题似乎是我没有使用正确的代码表,但到目前为止我所尝试的一切都没有取得任何成功。我想成功地替换/删除任何出现的'§'.

我也看了几篇"从字符串中删除字符"的帖子,但我没有找到任何帮助我的东西。

可执行代码:

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;

break into cstrPath = cstrPath;

根据评论,你混淆了Unicode和ANSI编码。看起来你的应用程序是针对Unicode的,这很好。您应该完全停止使用ANSI。

这样声明cInvalidChars:

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

使用L前缀意味着字符串字面值是一个宽字符UTF-16字面值。

那么你的循环可以像这样:

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