简体   繁体   中英

How to check if string contains single occurence of substring?

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?

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(ie the returned value is not -1).

您可以使用LINQ

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

替代

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

try like below... it 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());
    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");

另一种简单的选择

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

You can check the length (minus 1) of the array myString.Split('a') assuming that you're searching for the occurrences of 'a'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM