因为我的教授不会让我使用RegEx,所以我坚持使用循环来检查字符串上的每个字符.有没有人有示例代码/算法?
public void setAddress(string strAddress)
{
do
{
foreach (char c in Name)
{
if ( /*check for characters*/ == false)
{
Address = strAddress;
}
}
if ( /*check for characters*/ == true)
{
Console.Write("Invalid!");
}
} while ( /*check for characters*/ == true)
}
public int getAddress()
{
return Address;
}
Run Code Online (Sandbox Code Playgroud)
我只需要包含字母和数字.不允许使用!@#$%^等字符.我不被允许使用RegEx,因为他还没有教过我们......好吧,在他教这些循环和角色检查的那天我无法上课,所以现在他不会告诉我更多.无论如何,如果没有使用RegEx有更有效的方法,那将会有所帮助.
string s = @"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Run Code Online (Sandbox Code Playgroud)
你可以完全没有循环:)
资料来源:https://stackoverflow.com/a/4503614/1714342
编辑:
if(s.Any(c=>c => !Char.IsLetterOrDigit(c) || !Char.IsWhiteSpace(c))
{
Console.WriteLine("String contains special chars");
}
Run Code Online (Sandbox Code Playgroud)