C#中统计某个字符出现次数的最简单方法

两种方法都能有效地计算 "://" 在字符串中出现的次数

cs 复制代码
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 方法来计算特定子字符串的出现次数,这种方式更直观:

cs 复制代码
int count = text.Split(new[] { "://" }, StringSplitOptions.None).Length - 1;
相关推荐
阿蒙Amon44 分钟前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
i橡皮擦3 小时前
TheIsle恐龙岛读取游戏基址做插件(C#语言)
开发语言·游戏·c#·恐龙岛·theisle
用户21991679703919 小时前
C# 14 中的新增功能
c#
垂葛酒肝汤10 小时前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
爱说实话12 小时前
C# 20260112
开发语言·c#
无风听海12 小时前
C#中实现类的值相等时需要保留null==null为true的语义
开发语言·c#
云草桑12 小时前
海外运单核心泡货计费术语:不计泡、计全泡、比例分泡
c#·asp.net·net·计泡·海运
精神小伙就是猛13 小时前
C# Task/ThreadPool async/await对比Golang GMP
开发语言·golang·c#