如何检查字符串是否包含单个子串的出现?

时间:2013-02-08 15:01:14

标签: c# string

我有这个:

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

我需要类似string.Contains()的内容,但我不仅要知道字符串是否存在(如果是字母以上),还要如果是目前只有一个单一时间

我怎样才能做到这一点?

6 个答案:

答案 0 :(得分:14)

您可以使用LastIndexOf(String)IndexOf(String)并验证返回的值是否相等。当然还要检查是否找到了String(即返回的值不是-1)。

答案 1 :(得分:5)

您可以使用LINQ

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

答案 2 :(得分:1)

替代

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

答案 3 :(得分:0)

尝试如下......它会帮助你......

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());

答案 4 :(得分:0)

    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");

答案 5 :(得分:0)

另一个简单的选择:

Original string: ./dir1/dir2/dir3
Its parent directories:
./dir1
./dir1/dir2
./dir1/dir2/dir3
Next one if exists...

Original string: ./dir4/dir5
Its parent directories:
./dir4
./dir4/dir5
Next one if exists...