-1

I want to prevent two similar characters for example "@" to occur anywhere in my string. how i can do that .this is my string:

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

4 Answers4

2

In case of answer of Moo-Juice, you can use Linq in CounOf extension method:

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

If I understand correctly, you don't want more than one occurrence of a particular character in a string. You could write an extension method to return the count of a particular 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;
    }
}

Usage:

string email = "example@gmail.com";
string email2 = "example@gmail@gmail.com";
int c1 = email.CountOf('@'); // = 1
int c2 = email2.CountOf('@'); // = 2

What I really suspect you need, is email validation:

Regex Email validation

Community
  • 1
  • 1
Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
0

Try something like this:

if(!email.Contains("@"))
{
    // add the character
}
rhughes
  • 9,257
  • 11
  • 59
  • 87
  • i want to prevent two characters from inserting into string. – abazgiriabazgiri Mar 24 '13 at 15:11
  • @abazgiriabazgiri That is what this code does. `String.Contains` returns true if the string contains that character (or string). If it does not contain the character, then `String.Contains` returns false. – rhughes Mar 24 '13 at 15:13
0

You could use a regular expression...

if (Regex.Match(email, "@.*@")) {
    // Show error message
}
Glen Hughes
  • 4,712
  • 2
  • 20
  • 25