C# equivalent of Mid Function and a Mid Statement in Visual Basic

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.

  1.    /// <param name="newChar"> Character to be replaced.</param>  
  2.   
  3.    /// <returns></returns>  
  4.   
  5.    public static  string Mid(string input, int index, char newChar)  
  6.   
  7.    {  
  8.   
  9.        if (input == null)  
  10.   
  11.        {  
  12.   
  13.            throw new ArgumentNullException("input");  
  14.   
  15.        }  
  16.   
  17.        char[] chars = input.ToCharArray();  
  18.   
  19.        chars[index-1] = newChar;  
  20.   
  21.        return new string(chars);  
  22.   
  23.    }  
  24.   
  25.    /// <summary>  
  26.   
  27.    /// This is equivalent to Mid Function in VB6  
  28.   
  29.    /// </summary>  
  30.   
  31.    /// <param name="s"> String to Check.</param>  
  32.   
  33.    /// <param name="a">Position of Character</param>  
  34.   
  35.    /// <param name="b">Length </param>  
  36.   
  37.    /// <returns></returns>  
  38.   
  39.    public static string Mid(string s, int a, int b)  
  40.   
  41.    {  
  42.   
  43.        string temp = s.Substring(a - 1, b);  
  44.   
  45.        return temp;  
  46.   
  47.    }  
  48.   
  49. }  
Ebook Download
View all
Learn
View all