The article demonstrates the IndexOfAny() method to locate the initial occurrence of any string from a chosen array. Additionally, you utilize LastIndexOf() to pinpoint the last occurrence of a string within another string.
To enhance the complexity of the “message” variable by incorporating numerous sets of parentheses, followed by coding to extract the content enclosed within the last set of parentheses.
To begin, create a static class file called “StringMethodsPart2.cs” within the console application. Insert the provided code snippet into this file.
public static class StringMethodsPart2
{
/// <summary>
/// Outputs
/// Searching THIS message: Help (find) the {opening symbols}
/// Found WITHOUT using startPosition: (find) the { opening symbols }
/// </summary>
public static void IndexOfAnyMethod()
{
string message = "Help (find) the {opening symbols}";
Console.WriteLine($"Searching THIS Message: {message}");
char[] openSymbols = ['[', '{', '('];
int openingPosition = message.IndexOfAny(openSymbols);
Console.WriteLine($"Found WITHOUT using startPosition: {message.Substring(openingPosition)}");
}
}
Execute the code from the main method as follows
#region Day 7 - String built-in methods Part 2
StringMethodsPart2.IndexOfAnyMethod();
#endregion
set of parentheses
Utilize .IndexOfAny() to retrieve the index of the initial symbol from the openSymbols array that is present in the message string.
To do that, add another method into the same static class as shown below
/// <summary>
/// Outputs
/// set of parentheses
/// </summary>
public static void LastIndexOfMethod() {
string message = "(What if) I am (only interested) in the last (set of parentheses)?";
int openingPosition = message.LastIndexOf('(');
openingPosition += 1;
int closingPosition = message.LastIndexOf(')');
int length = closingPosition - openingPosition;
Console.WriteLine(message.Substring(openingPosition, length));
}
Execute the code from the main method as follows
#region Day 7 - String built-in methods Part 2
StringMethodsPart2.LastIndexOfMethod();
#endregion
Searching THIS message: Help (find) the {opening symbols}
Found WITHOUT using startPosition: (find) the {opening symbols}
GitHub — ssukhpinder/30DayChallenge.Net
Thank you for being a part of the C# community! Before you leave:
Follow us: X | LinkedIn | Dev.to | Hashnode | Newsletter | Tumblr
Visit our other platforms: GitHub | Instagram | Tiktok | Quora | Daily.dev
More content at C# Programming
Also published here.