一、实现步骤
- 遍历主字符串,使用
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(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;
}
}
quot;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
确保比较是基于原始字符串的字符顺序,不考虑文化或区域设置。