How to Truncate a string in C#?

This blog post will provide a simple tip demonstrating how you can implement a truncate function in C# so that value in a string gets truncated based on the given length.

How to Truncate a string in C#?

Out of the box , C# does not have any extension method called Truncate that works for this scenario. However, you can build a simple extension method in C# to truncate a string.

Here’s the Extension method that uses the Substring to fetch and truncate the results.

public static class StringExtension
{
    public static string Truncate(this string input, int strLength)
    {
        if (string.IsNullOrEmpty(input)) return input;
        return input.Length <= strLength ? input : input.Substring(0, strLength); 
    }
}

Complete Code Snippet is below.

public class Hello {
    public static void Main() {

        string input = "Welcome to DeveloperPublish.com";
        string truncatedString = input.Truncate(10);
        System.Console.WriteLine(truncatedString);
    }
}
public static class StringExtension
{
    public static string Truncate(this string input, int strLength)
    {
        if (string.IsNullOrEmpty(input)) return input;
        return input.Length <= strLength ? input : input.Substring(0, strLength); 
    }
}

Output

How to Truncate a string in C#?

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...