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

时间:2015-10-13 14:02:40

标签: c#

我是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
    }
}

提前致谢!

6 个答案:

答案 0 :(得分:4)

使用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)

答案 1 :(得分:1)

您可以使用正则表达式在一行中执行此操作:

Regex.IsMatch(myInput, @"^[a-zA-Z0-9\.\-]*$")

^                 -> match start of input
[a-zA-Z0-9\.\-]   -> match any of a-z , A-Z , 0-9, . or -
               *  -> 0 or more times (you may prefer + which is 1 or more times)
$                 -> match the end of input

答案 2 :(得分:0)

您可以使用Regex.IsMatch函数并指定正则表达式。

或者手动定义您需要的字符。像这样:

        string foo = "Hello!";

        char[] availableSymbols = {'-', ',', '!'};
        char[] availableLetters = {'A', 'a', 'H'}; //etc.
        char[] availableNumbers = {'1', '2', '3'}; //etc

        foreach (char c in foo)
        {
            if (availableLetters.Contains(c)) 
            {
                // Do what I want with letters
            }
            else if (availableNumbers.Contains(c))
            {
                // Do what I want with numbers
            }
            else if (availableSymbols.Contains(c))
            {
                // Do what I want with symbols
            }
        }

答案 3 :(得分:0)

可能的解决方案

您可以使用CharUnicodeInfo.GetUnicodeCategory(char)方法。它返回角色的UnicodeCategory。以下unicode类别可能是您要查找的内容:

  • UnicodeCategory.DecimalDigitNumber
  • UnicodeCategory.LowercaseLetterUnicodeCategory.UppercaseLetter

一个例子:

string foo = "Hello!";
foreach (char c in foo)
{  
    UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory(c);

    if (cat == UnicodeCategory.LowercaseLetter || cat == UnicodeCategory.UppercaseLetter)
    {
        // Do what I want with letters
    }
    else if (cat == UnicodeCategory.DecimalDigitNumber)
    {
        // Do what I want with numbers
    }
    else if (c == '-' || c == '.')
    {
        // Do what I want with symbols
    }
}

您的其他问题的答案

我可以删除== true部分吗?:

是的,您可以剪切== true部分,在C#

中不需要

如果还有'或',也包括句号。

要创建或表达,请使用' barbar' (||)运算符,如上所述。

答案 4 :(得分:0)

您可以将Regex.IsMatch与" ^ [a-zA-Z _。] * $"检查有效字符。

string foo = "Hello!";
if (!Regex.IsMatch(foo, "^[a-zA-Z_\.]*$"))
{
  throw new ArgumentException("Exception description here")
}

除此之外,您可以创建一个字符列表并使用string.Contains方法来检查它是否正常。

string validChars = "abcABC./";
foreach (char c in foo)
{
    if (!validChars.Contains(c))
    {
         // Throw exception
    }
}

此外,您不需要在if行中检查== true / false。两个表达式都等于

if (boolvariable) { /* do something */ }
if (boolvariable == true) { /* do something */ }

答案 5 :(得分:0)

每当你有一些类似的东西,一个数组,一个列表,一串字符,无论如何,你会在集合的定义中看到它实现了IEnumerable

public class String:...,IEnumerable,

这里T是一个char。这意味着你可以问全班:“给我你的第一个T”,“给我你的下一个T”,“给我你的下一个T”,依此类推,直到没有更多的元素。

这是所有 Linq 的基础。 Ling有大约40个作用于序列的函数。如果您需要对相同类型的项目执行某些操作,请考虑使用LINQ。

LINQ中的函数可以在Enumerable类中找到。其中一个功能是包含。您可以使用它来查明序列是否包含字符。

char [] allowedChars =“abcdefgh .... XYZ .-”。ToCharArray();

现在你有一系列允许的字符。假设您有一个字符x并想知道是否允许x:

char x = ...;
bool xIsAllowed = allowedChars.Contains(x);

现在假设您没有一个字符x,而是一个完整的字符串,并且您只想要允许此字符串中的字符:

string str = ...
var allowedInStr = str
    .Where(characterInString => allowedChars.Contains(characterInString));

如果您要对一系列事情做很多事情,请考虑花一些时间熟悉LINQ:

Linq explained