Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string contains single occurence of substring?

Tags:

string

c#

I have this:

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

And I need something similar to string.Contains(), but I need to know not only whether a string is present(in case above a letter), but also if it is present only ONE SINGLE time.

How can I achieve this?

like image 449
ojek Avatar asked Feb 08 '13 15:02

ojek


2 Answers

You can use LastIndexOf(String) and IndexOf(String) and verify that the values returned are equal. Of course also check if the String is found at all(i.e the returned value is not -1).

like image 52
Ivaylo Strandjev Avatar answered Nov 07 '22 06:11

Ivaylo Strandjev


You could use LINQ

int count = strings.Count(f => f == 'd');
like image 28
Andrew Beal Avatar answered Nov 07 '22 07:11

Andrew Beal