gpt4 book ai didi

c# - 如何检查字符串中每个字符的数据类型?

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:35 25 4
gpt4 key购买 nike

我是 C# 新手,所以可能会遇到一些错误。非常感谢任何帮助/指导。

我想将可接受的字符串输入限制为:

  • a-z
  • A-Z
  • 连字符
  • 时期

如果字符是字母、连字符或句号,则接受。任何其他内容都会返回错误。

我目前的代码是

string foo = "Hello!";
foreach (char c in foo)
{
/* Is there a similar way
To do this in C# as
I am basing the following
Off of my Python 3 knowledge
*/

if (c.IsLetter == true) // *Q: Can I cut out the == true part ?*
{
// Do what I want with letters
}
else if (c.IsDigit == true)
{
// Do what I want with numbers
}
else if (c.Isletter == "-") // Hyphen | If there's an 'or', include period as well
{
// Do what I want with symbols
}
}

我知道这是一组非常糟糕的代码。

写这篇文章的时候我有一个想法:是否可以创建一个允许的字符列表并根据该列表检查变量?

类似于:

foreach (char c in foo)
{
if (c != list)
{
// Unaccepted message here
}
else if (c == list)
{
// Accepted
}
}

提前致谢!

最佳答案

使用 Regex 即可轻松完成:

using System.Text.RegularExpressions;

var isOk = Regex.IsMatch(foo, @"^[A-Za-z0-9\-\.]+$");

纲要:

match from the start
| set of possible matches
| |
|+-------------+
|| |any number of matches is ok
|| ||match until the end of the string
|| |||
vv vvv
^[A-Za-z0-9\-\.]+$
^ ^ ^ ^ ^
| | | | |
| | | | match dot
| | | match hyphen
| | match 0 to 9
| match a-z (lowercase)
match A-Z (uppercase)

关于c# - 如何检查字符串中每个字符的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33104770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com