Very often when migrating traditional windows application written in VB6 ,we may come across the inbuild functions which were available in VB6 but not available in C# One such function is Mid Function.
Visual Basic has a Mid function and a Mid statement. These elements both operate on a specified number of characters in a string, but the Mid function returns the characters while the Mid statement replaces the characters.
Mid Function has following parameters
str
Start
Length
Target
Start
Length
StringExpression
Visual Basic has a Mid function and a Mid statement. These elements both operate on a specified number of characters in a string, but the Mid function returns the characters while the Mid statement replaces the characters.
Mid Function has following parameters
str
Required. String expression from which characters are returned.
Required. Integer expression. Starting position of the characters to return. If Start is greater than the number of characters in str, the Mid function returns a zero-length string (""). Start is one based.
Optional. Integer expression. Number of characters to return. If omitted or if there are fewer than Length characters in the text (including the character at position Start), all characters from the start position to the end of the string are returned.
Mid Statement
Replaces a specified number of characters in a String variable with characters from another string.
Mid Statement has following parametersReplaces a specified number of characters in a String variable with characters from another string.
Target
Required. Name of the String variable to modify.
Required. Integer expression. Character position in Target where the replacement of text begins. Start uses a one-based index.
Optional. Integer expression. Number of characters to replace. If omitted, all of String is used.
Required. String expression that replaces part of Target.
Here is the C# version for the same code.
/// <summary>/// Mid Statement and Mid Statement in C# /// </summary> public static class strMid { /// <summary> /// This is Equivalent to Mid Statement in VB6 /// </summary> /// <param name="input"> String to be altered.</param> /// <param name="index"> Location of character in string.</param> /// <param name="newChar"> Character to be replaced.</param> /// <returns></returns> public static string Mid(string input, int index, char newChar) { if (input == null) { throw new ArgumentNullException("input"); } char[] chars = input.ToCharArray(); chars[index-1] = newChar; return new string(chars); } /// <summary> /// This is equivalent to Mid Function in VB6 /// </summary> /// <param name="s"> String to Check.</param> /// <param name="a">Position of Character</param> /// <param name="b">Length </param> /// <returns></returns> public static string Mid(string s, int a, int b) { string temp = s.Substring(a - 1, b); return temp; } }