【发布时间】:2016-10-01 20:34:23
【问题描述】:
我正在尝试清除 C++ 中的字符串。我想为所有非字母字符清理它,并保持各种英文和非英文字母不变。我的一个测试代码看起来像这样
int main()
{
string test = "Danish letters: Æ Ø Å !!!!!!??||~";
cout << "Test = " << test << endl;
for(int l = 0;l<test.size();l++)
{
if(!isalpha(test.at(l)) && test.at(l) != ' ')
{
test.replace(l,1," nope");
}
}
cout << "Test = " << test << endl;
return 0;
}
这给了我输出:
Test = Danish letters: Æ Ø Å !!!!!!??||~
Test = Danish letters nope nope nope nope nope nope nope nope nope nope nope nope nope nope nope nope nope nope"
所以我的问题是,如何删除“!!!!!!??||~”而不是“Æ Ø Å”?
我也尝试过类似的测试
test.at(l)!='Å'
但我无法编译,如果我将 'Å' 声明为字符。
我读过有关 unicode 和 utf8 的内容,但我不是很了解。
请帮帮我:)
【问题讨论】:
-
嗯,你需要继续阅读有关 unicode 和 utf8 的内容,直到你理解它,然后一切都应该一清二楚。
-
您可能想查看标题为 How to strip all non alphanumeric characters from a string 的 SO 问题。我也有兴趣看看std::isalnum 是否适用于您的情况。
-
@RawN:这两个链接都只针对 ASCII,这个问题(隐含)是关于非 ASCII 的。
-
@MooingDuck 在 C++(或 C)中没有任何东西只适用于 ASCII。
-
@TomBlodget:从技术上讲,你是对的。从技术上讲,它们仅适用于字符编码的遗留子集。它们不适用于 Unicode 字符,此代码可能正在使用它。
标签: c++ string unicode special-characters