如何检查字符串是否包含单个子串的出现?
我有这个:
string strings = "abcdde";
我需要类似于string.Contains()
东西,但我不仅要知道字符串是否存在 (如果在字母上方),还要知道它是否仅存在一个单一时间 。
我怎样才能做到这一点?
您可以使用LastIndexOf(String)
和IndexOf(String)
并validation返回的值是否相等。 当然还要检查是否找到了String(即返回的值不是-1)。
您可以使用LINQ
int count = strings.Count(f => f == 'd');
替代
if(Regex.Matches(input,Regex.Escape(pattern)).Count==1)
尝试如下……它会帮助你……
string strings = "abcdde"; 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 = "abcdde"; 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)