我有一个很大的字符串需要解析,我需要找到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
= The listsource
= The large string有更好的主意吗?
发布于 2010-04-15 06:04:02
下面是它的一个示例扩展方法:
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);
}
}
如果您将其放入静态类中并使用using
导入名称空间,则它将显示为任何字符串上的方法,您只需执行以下操作:
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;
}
}
发布于 2010-04-15 09:04:31
为什么不使用内置的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参数更改为正则表达式matchExpression。
发布于 2010-04-15 10:38:54
使用LINQ
public static IEnumerable<int> IndexOfAll(this string sourceString, string subString)
{
return Regex.Matches(sourceString, subString).Cast<Match>().Select(m => m.Index);
}
https://stackoverflow.com/questions/2641326
复制相似问题