If we want to see if a string contains a certain text, we can use IndexOf, which tells us in what position it is (or -1 if it is not part of the string):
if (name.IndexOf("John") >= 0) Console.Write("Welcome, John");
We can add an optional second parameter, which is the position to start the search:
if (name.IndexOf("John", 5) >= 0) ...
The search finishes at the end of the string, unless we indicate a final position using an optional third parameter:
if (name.IndexOf("John", 5, 15) >= 0) ...
Similarly, LastIndexOf indicates the last occurrence (ie, looking from right to left).
No comments:
Post a Comment