📌  相关文章
📜  C#| StringCollection中首次出现的索引

📅  最后修改于: 2021-05-29 14:33:13             🧑  作者: Mango

StringCollection类是.NET Framework类库的新添加,它表示字符串的集合。 StringCollection类在System.Collections.Specialized命名空间中定义。
StringCollection.IndexOf(String)方法用于搜索指定的字符串,该字符串返回StringCollection中第一个匹配项的从零开始的索引。

句法:

public int IndexOf (string value);

在这里, value是要查找的字符串。该值可以为空。

返回值:该方法返回StringCollection中第一次出现的值的从零开始的索引,如果找到则否则返回-1。

注意:此方法执行线性搜索。因此,此方法是O(n)运算,其中n是Count。

下面的程序说明了StringCollection.IndexOf(String)方法的用法:

范例1:

// C# code to search string and returns
// the zero-based index of the first
// occurrence in StringCollection
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // creating a string array named myArr
        String[] myArr = new String[] { "A", "B", "C", "C", "D" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr);
  
        // To search string "C" and return
        // the zero-based index of the first
        // occurrence in StringCollection
        // Here, "C" exists at index 2 and 3.
        // But, the method should return 2
        Console.WriteLine(myCol.IndexOf("C"));
    }
}
输出:
2

范例2:

// C# code to search string and returns
// the zero-based index of the first
// occurrence in StringCollection
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // creating a string array named myArr
        String[] myArr = new String[] { "2", "3", "4", "5", "6" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr);
  
        // To search string "9" and return
        // the zero-based index of the first
        // occurrence in StringCollection
        // Here, "9" does not exist in myCol
        // Hence, method returns -1
        Console.WriteLine(myCol.IndexOf("9"));
    }
}
输出:
-1

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.stringcollection.indexof?view=netframework-4.7.2