C#中统计某个字符出现次数的最简单方法
两种方法都能有效地计算 "://"
在字符串中出现的次数
using System;public class Program
{public static void Main(){string text = "http://example.com and https://example.org";int count = (text.Length - text.Replace("://", "").Length) / "://".Length;Console.WriteLine($"'://' 出现的次数: {count}");}
}
更简洁的方法
如前所述,您也可以使用 String.Split
方法来计算特定子字符串的出现次数,这种方式更直观:
int count = text.Split(new[] { "://" }, StringSplitOptions.None).Length - 1;