英文:
char check that contains letters and digits
问题
我有一个以字符类型命名的变量,我目前正在使用以下代码来检查它是否只包含字母和数字:
public bool IsBroken() => _name.Any(c => !char.IsLetterOrDigit(c));
问题是,我的变量以A.A.A的形式命名,中间有点号,你有没有办法让点号也被允许,同时还包括字母和数字?
英文:
I have a name in char type, I am currently using the
public bool IsBroken() => _name.Any(c => !char.IsLetterOrDigit(c));
to check if it contains only letters and numbers.
problem is I have names in this form A.A.A with . in the middle, do you have an idea on how I can authorize the . also with letters and numbers
答案1
得分: 1
public bool IsBroken() => _name.Any(c => !(char.IsLetterOrDigit(c) || c == '.'));
英文:
public bool IsBroken() => _name.Any(c => !(char.IsLetterOrDigit(c) || c == '.'));
答案2
得分: 0
然后,您需要定义一些关于包含句点的名称的规则。如果一个名称以句点开头或以句点结尾,那么该方法应该返回true,因为该名称是不合法的;此外,如果一个名称中有连续的句点,也应该返回true,表示该名称是不合法的。我的下面的代码检查了连续的句点、名称开头或结尾的句点,以及输入字符串中不是数字或字母的字符。
public bool IsBroken(string _name)
{
// 检查名称是否以句点开头或以句点结尾
if (_name.StartsWith(".") || _name.EndsWith("."))
{
return true;
}
bool previousIsPeriod = false;
for (int i = 0; i < _name.Length; i++)
{
char c = _name[i];
// 检查是否为非字母和非数字字符
if (!char.IsLetterOrDigit(c) && !char.Equals(c, '.'))
{
return true;
}
// 检查名称中是否有连续的句点
if (char.Equals(c, '.'))
{
if (previousIsPeriod)
{
return true;
}
previousIsPeriod = true;
}
else
{
previousIsPeriod = false;
}
}
// 如果名称有效,返回false
return false;
}
希望这有助于您的需求。
英文:
Then you need to define some rules on the names that contain the periods. If a name starts or ends with a period then the method should return true because that name is broken, also if two consecutive periods are in a name then it should also return true that the name is broken. My code below checks for consecutive periods, periods at the beginning or end and character entries that are not a number or a letter in the input string.
public bool IsBroken(string _name)
{
//check if a name starts or ends with a period
if (_name.StartsWith(".") || _name.EndsWith("."))
{
return true;
}
bool previousIsPeriod = false;
for (int i = 0; i < _name.Length; i++)
{
char c = _name[i];
//check for non letter and non number characters
if (!char.IsLetterOrDigit(c) && !char.Equals(c, '.'))
{
return true;
}
//check for consecutive periods in the name
if (char.Equals(c, '.'))
{
if (previousIsPeriod)
{
return true;
}
previousIsPeriod = true;
}
else
{
previousIsPeriod = false;
}
}
//return false if the name is valid
return false;
}
答案3
得分: 0
你可以尝试使用正则表达式来检查。
public bool IsBroken() => !Regex.IsMatch(_name, @"^([a-zA-Z0-9]|[A-Z]\.)+$");
这里 有一个演示。
英文:
You can try checking that using Regular Expressions.
public bool IsBroken() => !Regex.IsMatch(_name, @"^([a-zA-Z0-9]|[A-Z]\.)+$");
Here is a demo.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论