我有一个大字符串需要解析,我需要找到 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);
}
}
如果你把它放到一个静态类中并使用 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;
}
}
关于c# - 在C#中查找较大字符串中子字符串的所有位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2641326/