Truncate a String in C#

This tutorial will introduce the method to truncate a string variable to a specified length in C#.

Truncate a String With the String.Substring() Method in C

Unfortunately, there is no built-in method to truncate a string in C#. We have to write code with our own logic for this purpose. The String.Substring(x, y) method retrieves a substring from the string that starts from the x index and has a length of y. We can use the String.Substring() method and the LINQ to create an extension method that works the string variable. The following code example shows us how to truncate a string variable with the String.Substring() method in C#.

using System;

namespace truncate_string
{
    public static class StringExt
    {
        public static string Truncate(this string variable, int Length)
        {
            if (string.IsNullOrEmpty(variable)) return variable;
            return variable.Length <= Length ? variable : variable.Substring(0, Length);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string variable = "This is a long, very long string and we want to truncate it.";
            variable = variable.Truncate(22);
            Console.WriteLine(variable);
        }
    }
}

Output:

This is a long, very l

In the above code, we truncated the string variable variable to a length of 22 characters with the String.Substring() method in C#. Then we created the extension method Truncate() that takes the desired length and truncates the string to the desired length. If the string variable is null or empty, the Truncate() method returns the string. If the desired length is greater than the length of the string, it returns the original string. If it is less, the Truncate() method truncates the string to the desired length with the String.Substring() method and returns the new truncated copy of the string.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp String

  • Generate Random Alphanumeric Strings in C#
  • Count Occurrences of a Character Inside a String in C#