当前位置: 首页 > news >正文

C# 使用LINQ找出一个子字符串在另一个字符串中出现的所有位置

一、实现步骤

  1. 遍历主字符串,使用IndexOf方法查找子字符串的位置。
  2. 如果找到了子字符串,记录其位置,并且从该位置的后面继续查找。
  3. 重复上述步骤直到遍历完整个字符串。

二、简单代码示例

using System;
using System.Collections.Generic;
using System.Linq;class Program
{static void Main(){string mainString = "Here is a test string, and here is another test string.";string substring = "test";var positions = FindAllSubstringPositions(mainString, substring);Console.WriteLine($"The substring '{substring}' is found at positions: {string.Join(", ", positions)}");}static List<int> FindAllSubstringPositions(string mainString, string substring){List<int> positions = new List<int>();int index = mainString.IndexOf(substring, StringComparison.Ordinal);while (index != -1){positions.Add(index);// Move to the next character after the found substring to avoid overlapping matches.index = mainString.IndexOf(substring, index + substring.Length, StringComparison.Ordinal);}return positions;}
}

中,FindAllSubstringPositions 方法使用IndexOf方法来查找子字符串的位置。如果找到了子字符串,它将位置添加到列表中,然后从找到的位置的后面继续搜索,以避免重复计数。这个过程一直持续到整个主字符串都被检查完毕。

请注意,IndexOf方法的第三个参数允许你指定搜索的起始位置,这使得我们可以在找到子字符串后从正确的位置继续搜索。StringComparison.Ordinal确保比较是基于原始字符串的字符顺序,不考虑文化或区域设置。

http://www.lryc.cn/news/423158.html

相关文章:

  • YOLOv8添加MobileViTv3模块(代码+free)
  • 从概念到落地:全面解析DApp项目开发的核心要素与未来趋势
  • 仓颉编程入门 -- 泛型概述 , 如何定义泛型函数
  • SOC估算方法之(OCV-SOC+安时积分法)
  • 指针(下)
  • C# 浅谈IEnumerable
  • mmdebstrap:创建 Debian 系统 chroot 环境的利器 ️
  • 【Linux SQLite数据库】一、SQLite交叉编译与移植
  • 每天写两道(数组篇)移除元素、
  • Unity 使用 NewtonSoft Json插件报错
  • k8s 部署 Mysqld_exporter 以及添加告警规则
  • 基于STM32开发的智能农业环境监测系统
  • 【SQL】平均售价
  • 存储器与CPU的连接
  • unity--webgl 访问本地index.html
  • 慢慢欣赏DPDK RTE_MAX_ETHPORTS的定义
  • Java Nacos与Gateway的使用
  • 前端项目中的Server-sent Events(SSE)项目实践及其与websocket的区别
  • 《老俞闲话|唯爱和热情不可辜负》读后感
  • C语言 ——— 在杨氏矩阵中查找具体的某个数
  • DAI-Net: 基于对偶自适应交互网络的药物推荐算法
  • haproxy高级功能及配置
  • 【前端】NodeJS:记账本案例优化(MongoDB数据库)
  • Padding Mask;Sequence Mask;为什么如果没有适当的掩码机制,解码器在生成某个位置的输出时,可能会“看到”并错误地利用该位置之后的信息
  • 派森学长带你学python—字典
  • 如何设置 Visual Studio Code 的滚轮缩放功能
  • Python模拟退火算法
  • C语言典型例题36
  • 实现高亮的全文分页检索
  • 【buildroot与yocto区别】