我有一个类似于这样的字符串:
"7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"
我想做的是计算字符串中出现 "true" 的次数。我感觉答案应该是像 String.CountAllTheTimesThisStringAppearsInThatString()
这样,但出于某种原因我就是想不出来。请帮帮忙?
我有一个类似于这样的字符串:
"7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false"
我想做的是计算字符串中出现 "true" 的次数。我感觉答案应该是像 String.CountAllTheTimesThisStringAppearsInThatString()
这样,但出于某种原因我就是想不出来。请帮帮忙?
Regex.Matches(input, "true").Count
input
,它不是正则表达式啊? - tpowerRegex.Escape
并在LINQPad中运行了测试以确认。我编辑了编辑内容以删除它。 - Chris Benard可能不是最有效的方法,但我认为这是一个很好的做法。
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;
}
}
你的正则表达式应该是\btrue\b
,以解决Casper提出的“miscontrue”问题。完整的解决方案如下:
你的正则表达式应该是\btrue\b
,以解决Casper提出的“miscontrue”问题。完整的解决方案如下:
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" 这样的字符串,则此方法将失败。
Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count;
这里,我将使用LINQ来过度设计回答。这只是展示了煮鸡蛋的方法不止一种:
public int countTrue(string data)
{
string[] splitdata = data.Split(',');
var results = from p in splitdata
where p.Contains("true")
select p;
return results.Count();
}
With Linq...
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”定义正则表达式才能执行此操作!
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