String extension method which returns first N characters of the input string. - CSharp System

CSharp examples for System:Char

Description

String extension method which returns first N characters of the input string.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;//w  w  w. j  a va  2  s.  c om

public class Main{
        /// <summary>
        /// String extension method which returns first N characters of the input string.
        /// </summary>
        /// <param name="input">The string on which the method is invoked.</param>
        /// <param name="charsCount">The count of the characters to be returned.</param>
        /// <returns>Returns the beginning of the input string as a substring with lenght equals to charsCount. If the charsCount is greater than the lenght of the input string, returns whole string.</returns>
        public static string GetFirstCharacters(this string input, int charsCount)
        {
            return input.Substring(0, Math.Min(input.Length, charsCount));
        }
}

Related Tutorials