Count the number of times a string appears within a string
本问题已经有最佳答案,请猛点这里访问。
我只是有一根像这样的绳子:
"7,对,不适用,错:67,错,不适用,错:5,错,不适用,错:5,错,不适用,错"
我只想计算字符串"true"在该字符串中出现的次数。我觉得答案有点像
1 | Regex.Matches(input,"true").Count |
也许不是最有效的方法,但你认为这是一个很好的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Program { static void Main(string[] args) { Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false","true")); Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false","false")); } static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find) { var s2 = orig.Replace(find,""); return (orig.Length - s2.Length) / find.Length; } } |
您的正则表达式应该是
1 2 3 | string searchText ="7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"; string regexPattern = @"\btrue\b"; int numberOfTrues = Regex.Matches(searchText, regexPattern).Count; |
确保文件顶部包含System.Text.RegularExpressions命名空间。
但如果字符串可以包含"miscontrue"这样的字符串,则此操作将失败。
1 | Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false","true").Count; |
在这里,我将使用LINQ重新设计答案。这表明有很多种方法可以煮鸡蛋:
1 2 3 4 5 6 7 8 9 10 | public int countTrue(string data) { string[] splitdata = data.Split(','); var results = from p in splitdata where p.Contains("true") select p; return results.Count(); } |
用LINQ…
1 2 | string s ="7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"; var count = s.Split(new[] {',', ':'}).Count(s => s =="true" ); |
执行此操作时,请注意必须为"test"定义regex!!!!
1 2 3 | string s ="7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"; string[] parts = (new Regex("")).Split(s); //just do a count on parts |