The module demonstrates string-helper methods to pinpoint and extract the desired information.
Utilize the IndexOf() method to find the position of a single or multiple characters/strings within a larger string.
To begin, create a static class file called “StringMethods.cs” within the console application. Insert the provided code snippet into this file.
public static class StringMethods { /// <summary> /// Outputs /// 13 /// 36 /// </summary> public static void IndexOfExample() { string message = "Find what is (inside the parentheses)";
int openingPosition = message.IndexOf('(');
int closingPosition = message.IndexOf(')');
Console.WriteLine(openingPosition);
Console.WriteLine(closingPosition);
}
}
Execute the code from the main method as follows
#region Day 6 - String built-in methods
StringMethods.IndexOfExample();
#endregion
13 36
Use the Substring() method to extract the part of the main string that comes after the specified character positions.
To do that, add another method into the same static class as shown below
/// <summary>
/// Outputs
/// (inside the parentheses
/// </summary>
public static void SubstringExample()
{
string message = "Find what is (inside the parentheses)";
int openingPosition = message.IndexOf('(');
int closingPosition = message.IndexOf(')');
int length = closingPosition - openingPosition;
Console.WriteLine(message.Substring(openingPosition, length));
Execute the code from the main method as follows
#region Day 6 - String built-in methods
StringMethods.SubstringExample();
#endregion
(inside the parentheses
Simply update the starting index position using openingPosition += 1; To do that, add another method into the same static class as shown below
/// <summary>
/// Outputs
/// inside the parentheses
/// </summary>
public static void SubstringExample2()
{
string message = "Find what is (inside the parentheses)";
int openingPosition = message.IndexOf('(');
int closingPosition = message.IndexOf(')');
openingPosition += 1;
int length = closingPosition - openingPosition;
Console.WriteLine(message.Substring(openingPosition, length));
}
Execute the code from the main method as follows
#region Day 6 - String built-in methods
StringMethods.SubstringExample2();
#endregion
inside the parentheses
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.