How can I check if a string contains a single occurrence of a substring?

I have it:

string strings = "a b c d d e";

      

And I need something similar to string.Contains()

, but I need to know not only if the string is present (in the case above the letter), but also if it is present only ONE SINGLE time .

How can I achieve this?

+3


source to share


6 answers


You can use LastIndexOf(String)

and IndexOf(String)

and make sure the return values ​​are equal. Of course, also check if the String is found at all (i.e. the return value is not -1).



+13


source


You can use LINQ



int count = strings.Count(f => f == 'd');

      

+4


source


Alternative

if(Regex.Matches(input,Regex.Escape(pattern)).Count==1)

      

+1


source


try as below ... this will help you ...

string strings = "a b c d d e";
string text ="a";
int count = 0;
int i = 0;
while ((i = strings.IndexOf(text, i)) != -1)
{
    i += text.Length;
    count++;
}
if(count == 0)
Console.WriteLine("String not Present");

if(count == 1)
Console.WriteLine("String Occured Only one time");

if(Count>1)
Console.WriteLine("String Occurance : " + count.Tostring());

      

0


source


    string source = "a b c d d e";
    string search = "d";
    int i = source.IndexOf(search, 0);
    int j = source.IndexOf(search, i + search.Length);
    if (i == -1)
        Console.WriteLine("No match");
    else if (j == -1)
        Console.WriteLine("One match");   
    else
        Console.WriteLine("More match");

      

0


source


Another simple alternative:

if(strings.Split(new [] { "a" }, StringSplitOptions.None).Length == 2)

      

0


source







All Articles