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";
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";
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);
}
}
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:
Try something like this:
if(!email.Contains("@"))
{
// add the character
}
You could use a regular expression...
if (Regex.Match(email, "@.*@")) {
// Show error message
}