C# | Index of first occurrence in StringCollection
StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.
StringCollection.IndexOf(String) method is used to search the specified string which returns the zero-based index of the first occurrence within the StringCollection.
Syntax:
public int IndexOf (string value);
Here, value is the string to locate. The value can be null.
Return Value: The method returns zero-based index of the first occurrence of value in the StringCollection, if found otherwise it returns -1.
Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count.
Below programs illustrate the use of StringCollection.IndexOf(String) method:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
String[] myArr = new String[] { "A" , "B" , "C" , "C" , "D" };
myCol.AddRange(myArr);
Console.WriteLine(myCol.IndexOf( "C" ));
}
}
|
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
String[] myArr = new String[] { "2" , "3" , "4" , "5" , "6" };
myCol.AddRange(myArr);
Console.WriteLine(myCol.IndexOf( "9" ));
}
}
|
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...