Very often when migrating traditional windows application written in VB6, we may come across the inbuilt 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
Required. String from which characters will be returned.
Start
Required. Integer. Start position of the characters to be returned. If Start position is greater than the number of characters in str, the Mid function returns a zero-length string (""). Start is one based.
Length
Optional. Integer. Number of characters to be returned. If this parameter is omitted or if number of characters is less than length of 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 the following parameters.
Target
Required. Name of the String variable to be modified.
Start
Required. Integer. Position in target where the replacement of text begins. Start uses a one-based index.
Length
Optional. Integer. Number of characters to be replaced. If this parameter is omitted, all of the String is used.
StringExpression
Required. String expression that replaces part of Target.
Here is the C# version for the same code.
-
-
-
-
- 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);
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static string Mid(string s, int a, int b)
-
- {
-
- string temp = s.Substring(a - 1, b);
-
- return temp;
-
- }
-
- }