У меня есть большая строка, которую я должен проанализировать, и я должен найти все экземпляры extract"(me,i-have lots. of]punctuation
, и сохраните индекс каждого к списку.
Поэтому выскажите свое мнение строки, был в начале и середине большей строки, они оба будут найдены, и их индексы были бы добавлены к List
. и List
содержал бы 0
и другой индекс вообще это было бы.
Я играл вокруг, и string.IndexOf
делает почти, что я ищу, и я написал некоторый код - но он не работает, и я не мог выяснить точно что не так:
List<int> inst = new List<int>();
int index = 0;
while (index < source.LastIndexOf("extract\"(me,i-have lots. of]punctuation", 0) + 39)
{
int src = source.IndexOf("extract\"(me,i-have lots. of]punctuation", index);
inst.Add(src);
index = src + 40;
}
inst
= Списокsource
= Большая строкаКакие-либо лучшие идеи?
Вот пример метода расширения для него:
public static List<int> AllIndexesOf(this string str, string value) {
if (String.IsNullOrEmpty(value))
throw new ArgumentException("the string to find may not be empty", "value");
List<int> indexes = new List<int>();
for (int index = 0;; index += value.Length) {
index = str.IndexOf(value, index);
if (index == -1)
return indexes;
indexes.Add(index);
}
}
Если вы поместите это в статический класс и импортируете пространство имен с помощью , используя
, он отображается как метод в любой строке, и вы можете просто:
List<int> indexes = "fooStringfooBar".AllIndexesOf("foo");
Для получения дополнительной информации о методах расширения, http://msdn.microsoft.com/en-us/library/bb383977.aspx
То же самое с итератором:
public static IEnumerable<int> AllIndexesOf(this string str, string value) {
if (String.IsNullOrEmpty(value))
throw new ArgumentException("the string to find may not be empty", "value");
for (int index = 0;; index += value.Length) {
index = str.IndexOf(value, index);
if (index == -1)
break;
yield return index;
}
}
Почему вы не используете встроенный класс RegEx:
public static IEnumerable<int> GetAllIndexes(this string source, string matchString)
{
matchString = Regex.Escape(matchString);
foreach (Match match in Regex.Matches(source, matchString))
{
yield return match.Index;
}
}
Если вам нужно повторно использовать выражение, то скомпилируйте его и кэшируйте где-нибудь. Измените параметр matchString на Regex matchExpression в другой перегрузке для случая повторного использования.
с использованием LINQ
public static IEnumerable<int> IndexOfAll(this string sourceString, string subString)
{
return Regex.Matches(sourceString, subString).Cast<Match>().Select(m => m.Index);
}
public List<int> GetPositions(string source, string searchString)
{
List<int> ret = new List<int>();
int len = searchString.Length;
int start = -len;
while (true)
{
start = source.IndexOf(searchString, start + len);
if (start == -1)
{
break;
}
else
{
ret.Add(start);
}
}
return ret;
}
Назовите это так:
List<int> list = GetPositions("bob is a chowder head bob bob sldfjl", "bob");
// list will contain 0, 22, 26
Исходя из кода, который я использовал для поиска нескольких экземпляров строки в более крупной строке, ваш код будет выглядеть так:
List<int> inst = new List<int>();
int index = 0;
while (index >=0)
{
index = source.IndexOf("extract\"(me,i-have lots. of]punctuation", index);
inst.Add(index);
index++;
}