You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ReadOnlySpan<char>指定索引处检测匹配字符串?

解决方案:ReadOnlySpan指定索引匹配目标字符串

可以通过边界合法性检查 + Span切片比较实现零内存分配的单行Lambda实现,核心逻辑先确认索引位置合法且剩余长度足够容纳目标模式,再截取对应片段做相等比较:

public bool Test(ReadOnlySpan<char> span, int index, ReadOnlySpan<char> pattern) 
    => index >= 0 && index + pattern.Length <= span.Length && span.Slice(index, pattern.Length).SequenceEqual(pattern);

逻辑说明

  • index >= 0:确保起始索引不小于0,避免负索引越界
  • index + pattern.Length <= span.Length:确保从指定索引开始,原Span剩余长度足够容纳整个目标模式,防止切片时越界
  • span.Slice(index, pattern.Length).SequenceEqual(pattern):截取原Span中对应位置的片段,与目标模式执行零内存分配的相等比较

完整测试示例

var span = "FooBarBazBizzBuzz".AsSpan();
Assert.IsTrue(Test(span, 9, "Bizz".AsSpan()));

public bool Test(ReadOnlySpan<char> span, int index, ReadOnlySpan<char> pattern) 
    => index >= 0 && index + pattern.Length <= span.Length && span.Slice(index, pattern.Length).SequenceEqual(pattern);

内容的提问来源于stack exchange,提问作者NWoodsman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 12:52:07