计算字符串在字符串中出现的次数

one*_*ney 55 c# string count

我只是有一个看起来像这样的字符串:

"7,真实,NA,假:67,假,NA,假:5,假,NA,假:5,假,NA,假"

我想要做的就是计算字符串" true "出现在该字符串中的次数.我觉得答案是这样的,String.CountAllTheTimesThisStringAppearsInThatString()但由于某种原因,我无法弄明白.救命?

µBi*_*Bio 175

Regex.Matches(input, "true").Count
Run Code Online (Sandbox Code Playgroud)

  • 仅基于简洁 - 你赢了;) (2认同)

rjd*_*eux 14

可能不是最有效的,但认为这是一种巧妙的方式.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 哈哈 - 我应该用你提出的方法名称来标记你的.:) (2认同)

Don*_*Ray 13

你的正则表达应该是\btrue\b解决Casper提出的"误解"问题.完整的解决方案如下所示:

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;
Run Code Online (Sandbox Code Playgroud)

确保System.Text.RegularExpressions命名空间包含在文件的顶部.


Spl*_*ofy 5

如果字符串可以包含"miscontrue"之类的字符串,则会失败.

   Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count;
Run Code Online (Sandbox Code Playgroud)


Rob*_*cus 5

在这里,我将使用 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();
}
Run Code Online (Sandbox Code Playgroud)