更新时间:2023-11-02 22:30:46
这是它的扩展方法示例:
Here's an example extension method for it:
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
导入命名空间,它会在任何字符串上显示为一个方法,你可以这样做:
If you put this into a static class and import the namespace with using
, it appears as a method on any string, and you can just do:
List<int> indexes = "fooStringfooBar".AllIndexesOf("foo");
有关扩展方法的更多信息,http://msdn.microsoft.com/en-us/library/bb383977.aspx
For more information on extension methods, 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;
}
}