HomeCSharpHow to Truncate a string in C#?

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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...