问题描述
这是代码:
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),“ _”(下划线)和“-”(连字符)。如果情况是要检查那些允许的条件。
如果它不在允许的条件下,它将删除它。
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 '\0'
2. using ' ' (space in between ' ')
3. using ""[0]
但这会在替换时引入空间。
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;
}