C# 如何防止两个相似的字符同时出现在字符串中的任何位置

C# 如何防止两个相似的字符同时出现在字符串中的任何位置,c#,string,C#,String,我想防止字符串中出现两个类似的字符,例如“@”。 这是我的字符串: static string email = " example@gmail.com"; 试着这样做: if(!email.Contains("@")) { // add the character } 如果我理解正确,您不希望字符串中出现一个以上的特定字符。您可以编写一个扩展方法来返回特定字符的计数: public static class Extensions { public static int

我想防止字符串中出现两个类似的字符,例如“@”。 这是我的字符串:

    static string email = " example@gmail.com";

试着这样做:

if(!email.Contains("@"))
{
    // add the character
}

如果我理解正确,您不希望字符串中出现一个以上的特定字符。您可以编写一个扩展方法来返回特定字符的计数:

public static class Extensions
{
    public static int CountOf(this string data, Char c)
    {
        int count = 0;
        foreach(Char chk in data)
        {
            if(chk == c)
               ++count;
        }
        return count;
    }
}
用法:

string email = "example@gmail.com";
string email2 = "example@gmail@gmail.com";
int c1 = email.CountOf('@'); // = 1
int c2 = email2.CountOf('@'); // = 2
我怀疑您真正需要的是电子邮件验证:


您可以使用正则表达式

if (Regex.Match(email, "@.*@")) {
    // Show error message
}

如果回答Moo Juice,您可以使用Linq In CONCOUNOF扩展方法:

public static class Extensions
{
    public static int CountOf(this string data, Char c)
    {
        return string.IsNullOrEmpty(data) ? 0 : data.Count(chk => chk == c);
    }
}

“阻止”是什么意思?字符串不接受字符。我想阻止在字符串中插入两个字符。@abazgirabazgiri这就是代码的作用
String.Contains
如果字符串包含该字符(或字符串),则返回true。如果不包含字符,则
String.Contains
返回false。