第一种:IndexOf 循环查找
public int[] GetSubStrCountInStr(String str, String substr, int StartPos)
{
int foundPos = -1;
int count = 0;
List<int> foundItems = new List<int>();
do
{
foundPos = str.IndexOf(substr, StartPos);
if (foundPos > -1)
{
StartPos = foundPos + 1;
count++;
foundItems.Add(foundPos);
}
} while (foundPos > -1 && StartPos < str.Length);
return ((int[])foundItems.ToArray());
}
第二种:Linq 查找
string temp = "12334536"; 查3出现的位置
List<int> temp_index = temp.Select((item, index) => new { item, index }).Where(t => t.item == '3').Select(t => t.index).ToList();
本文介绍了两种在C#中实现字符串查找的方法:使用IndexOf进行循环查找和利用Linq进行位置索引的筛选。这两种方法都能有效定位子字符串在目标字符串中的位置,并返回所有匹配项的索引。
554

被折叠的 条评论
为什么被折叠?



