To extract substring C# provides substring method.But unlike VB.NET in C# there is no left and right methods to extract left and right substrings.
If we need to extract left and right substrings then we need to write custom logic to extract left and right side substrings.
Left and Right substring methods in C#
Following class is an extension class which declares the methods called ExtractLeft and ExtractRight to extract left and right substrings from the main string.
public static class StringExt { public static string ExtractLeft(this string originalString, int nofChars) { //retrun left string string leftString = originalString.Substring(0, nofChars); return leftString; } public static string ExtractRight(this string originalString, int nofChars) { //retrun right string abcdefg string result = originalString.Substring(originalString.Length - nofChars, nofChars); return result; } }
We are calling the above methods in the following example:
string leftStr = "This is a sample string"; string leftchars=leftStr.ExtractLeft(2); string rightchars = leftStr.ExtractRight(5);
we get the following return values in the above example
ng
tring
Leave a Reply