重庆璧山网站建设,菏泽网站建设 梧桐树,相城网页设计,旅游网页制作模板教程一、实现步骤
遍历主字符串#xff0c;使用IndexOf方法查找子字符串的位置。如果找到了子字符串#xff0c;记录其位置#xff0c;并且从该位置的后面继续查找。重复上述步骤直到遍历完整个字符串。 二、简单代码示例 using System;
using System.Collections.Generic;
usi…一、实现步骤
遍历主字符串使用IndexOf方法查找子字符串的位置。如果找到了子字符串记录其位置并且从该位置的后面继续查找。重复上述步骤直到遍历完整个字符串。 二、简单代码示例 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 Listint FindAllSubstringPositions(string mainString, string substring){Listint positions new Listint();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确保比较是基于原始字符串的字符顺序不考虑文化或区域设置。