C# में String.IndexOf() मेथड इस इंस्टेंस में निर्दिष्ट यूनिकोड कैरेक्टर या स्ट्रिंग की पहली घटना का जीरो-आधारित इंडेक्स ढूंढता है। नहीं मिलने पर -1 लौटाता है।
सिंटैक्स
public int IndexOf (string value);
पैरामीटर value खोजी जाने वाली स्ट्रिंग है।
उदाहरण 1: कैरेक्टर इंडेक्स ढूंढना
using System;
public class Demo {
public static void Main(String[] args) {
string str1 = "Jacob";
string str2 = "John";
Console.WriteLine("String 1 = " + str1);
Console.WriteLine("HashCode of String 1 = " + str1.GetHashCode());
Console.WriteLine("Index of 'o' in str1 = " + str1.IndexOf("o"));
Console.WriteLine("\nString 2 = " + str2);
Console.WriteLine("HashCode of String 2 = " + str2.GetHashCode());
Console.WriteLine("Index of 'o' in str2 = " + str2.IndexOf("o"));
bool res = str1.Contains(str2);
if (res)
Console.WriteLine("Found!");
else
Console.WriteLine("Not found!");
}
}
आउटपुट
String 1 = Jacob HashCode of String 1 = -790718923 Index of 'o' in str1 = 3 String 2 = John HashCode of String 2 = -1505962600 Index of 'o' in str2 = 1 Not found!
उदाहरण 2: मौजूद न होने वाले कैरेक्टर की खोज
using System;
public class Demo {
public static void Main(String[] args) {
string str1 = "Kevin";
string str2 = "Evin";
Console.WriteLine("String 1 = " + str1);
Console.WriteLine("HashCode of String 1 = " + str1.GetHashCode());
Console.WriteLine("Index of 'k' in str1 = " + str1.IndexOf("k"));
Console.WriteLine("\nString 2 = " + str2);
Console.WriteLine("HashCode of String 2 = " + str2.GetHashCode());
Console.WriteLine("Index of 'k' in str2 = " + str2.IndexOf("k"));
bool res = str1.Contains(str2);
if (res)
Console.WriteLine("Found!");
else
Console.WriteLine("Not found!");
}
}
आउटपुट
String 1 = Kevin HashCode of String 1 = -768104063 Index of 'k' in str1 = -1 String 2 = Evin HashCode of String 2 = 1223510568 Index of 'k' in str2 = -1 Not found!
IndexOf के अन्य ओवरलोड्स
| मेथड | विवरण |
|---|---|
IndexOf(char) | कैरेक्टर खोजें |
IndexOf(string) | सबस्ट्रिंग खोजें |
IndexOf(char, int) | निर्दिष्ट इंडेक्स से कैरेक्टर खोजें |
IndexOf(string, int) | निर्दिष्ट इंडेक्स से सबस्ट्रिंग खोजें |
IndexOf(char, int, int) | रेंज में कैरेक्टर खोजें |
IndexOf(string, int, int) | रेंज में सबस्ट्रिंग खोजें |
IndexOf(..., StringComparison) | तुलना विकल्पों के साथ खोजें |
महत्वपूर्ण बिंदु
- केस-सेंसिटिव खोज डिफ़ॉल्ट है।
- केस-इनसेंसिटिव के लिए
StringComparison.OrdinalIgnoreCaseउपयोग करें। LastIndexOf()अंतिम घटना ढूंढता है।- नहीं मिलने पर -1 लौटाता है (अपवाद नहीं फेंकता)।
उदाहरण: केस-इनसेंसिटिव खोज
string text = "Hello World";
int index = text.IndexOf("world", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(index); // 6