HasMultipleInstancesOf
Determines whether a string has multiple occurrences of a particular character. May be helpful when parsing file names, or ensuring a particular string has already contains a given character. This may be extended to use strings, rather than a char.
Source
public static partial class StringExtensions
{
public static bool HasMultipleInstancesOf(this string input, char charToFind)
{
if ((string.IsNullOrEmpty(input)) || (input.Length == 0) || (input.IndexOf(charToFind) == 0))
return false;
if (input.IndexOf(charToFind) != input.LastIndexOf(charToFind))
return true;
return false;
}
}
Example
string myStr1= "Hello.World.txt";
string myStr2= "Hello World";
bool hasMultPeriods = myStr1.HasMultipleInstancesOf('.'); //returns true
bool hasMultSpaces = myStr2.HasMultipleInstancesOf(' '); //returns false