ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Left

Returns the first few characters of the string with a length specified by the given parameter. If the string's length is less than the given length the complete string is returned. If length is zero or less an empty string is returned

Source

/// <summary>
/// Returns the first few characters of the string with a length
/// specified by the given parameter. If the string's length is less than the 
/// given length the complete string is returned. If length is zero or 
/// less an empty string is returned
/// </summary>
/// <param name="s">the string to process</param>
/// <param name="length">Number of characters to return</param>
/// <returns></returns>
public static string Left(this string s, int length)
{
    length = Math.Max(length, 0);

    if (s.Length > length)
    {
        return s.Substring(0, length);
    }
    else
    {
        return s;
    }
}

Example

string s = "abcde";

s = s.Left(2);    //s becomes "ab"

Author: C.F.Meijers

Submitted on: 11 dec. 2007

Language: C#

Type: System.String

Views: 11609