我有这个:
string strings = "a b c d d e";
我需要类似于
string.Contains()
的函数,但我不仅需要知道一个字符串是否存在(在上面的例子中是一个字母),还需要知道它是否仅出现一次。我该如何实现这个功能?
你可以使用LastIndexOf(String)
和IndexOf(String)
方法,并验证它们返回的值是否相等。当然,也要检查该字符串是否被找到(即返回值不是-1)。
您可以使用LINQ
int count = strings.Count(f => f == 'd');
if(strings.Split(new [] { "a" }, StringSplitOptions.None).Length == 2)
if(Regex.Matches(input,Regex.Escape(pattern)).Count==1)
尝试像下面这样...它会帮助你...
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());
strings
和text
变量。例如,当你说text.IndexOf(text, i)
时。请注意,如果搜索字符串存在两个重叠的子字符串,这可能是有趣的。比如在字符串"XXXXXreassureassureXX"
中搜索子字符串"reassure"
,可能希望计算出两个匹配项(问题不清楚)。所以要注意你增加i
的数量。同时也要注意i
的增量,因为如果超出了strings
变量的边界,下一个IndexOf
将抛出异常,而不仅仅返回-1
。 - Jeppe Stig Nielsenstrings = "a b c d d e"
和 text = "e"
测试您的代码。修复问题后,再使用 strings = "XXXXXreassureassureXX"
和 text = "reassure"
进行测试。在这种情况下,您更喜欢哪个答案? - Jeppe Stig Nielsen 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");
假设您正在搜索'a'的出现次数,您可以检查数组myString.Split('a')的长度(减1)
GroupBy
和OrderDescending
。 - MethodMan