Start learning free

LESSON 61 OF 674 · STRINGS I

String Find in C#

Lesson

In C#, you can find the index of a substring using IndexOf():

s.IndexOf(sub)           // returns index of first occurrence, or -1 if not found
s.LastIndexOf(sub)       // returns index of last occurrence
s.IndexOf(sub, fromIdx)  // search starting from index `fromIdx`

Here are some examples:

string sentence = "Hello World";
int idx = sentence.IndexOf("World");
Console.WriteLine(idx);  // 6

Console.WriteLine(sentence.IndexOf("xyz"));  // -1  (not found)

The index returned is the position of the first character of the found substring.


Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!


Hint
Use sentence.IndexOf("World") and assign the result to idx.

STEP 1 OF 1
    Ctrl + Enter to check