数字符串
中出现的字符串的次数我只是有一个字符串,它看起来是这样的:数字符串
“7,真实,NA,假:67,假的,NA,假:5,假的, NA,假:5,假的,NA,假”
所有我想要做的是算多少次字符串‘真正’出现在该字符串。我感觉就像String.CountAllTheTimesThisStringAppearsInThatString()
的答案,但由于某种原因,我只是无法弄清楚。帮帮我?
这将失败,虽然如果字符串可以包含像“miscontrue”字符串。
Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count;
这样做,请注意,您将不得不为'测试'定义正则表达式!
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
使用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");
你的正则表达式应该是\btrue\b
,以绕过 '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名称空间包含在文件的顶部。
字符串变量不应该被称为正则表达式 - 它会与.NET Regex类名称本身发生冲突。 – JustAMartin 2015-04-08 16:42:42
可能不是最有效的,但认为这是一个干净的方式来做到这一点。
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;
}
}
哈哈 - 为了使用我提出的方法名称,我应该将你的标记标记为正确。 :) – onekidney 2010-06-11 18:58:42
在这里,我将使用LINQ过度构建答案。只是表明有比“N”的方式更煮鸡蛋:
public int countTrue(string data)
{
string[] splitdata = data.Split(',');
var results = from p in splitdata
where p.Contains("true")
select p;
return results.Count();
}
感谢它的工作很好,也很聪明:) – Syed 2014-08-14 09:15:00
http://stackoverflow.com/questions/541954/how-would-you-count-occurences-of-a-string-within -a-string -c/542136#542136 – jball 2010-06-10 16:59:59
@jball我认为所有的解决方案都用于计算*字符的出现* – AakashM 2010-06-10 17:56:23
@AakashM,看看第二个链接。此外,这是为该问题提供更正确(即基于字符串,不基于字符)答案的绝佳机会。 – jball 2010-06-10 18:46:14