How To Truncate String Using C#?

In C#, you can truncate a string to a specified length using various methods. Here’s a simple example demonstrating different approaches:

using System;

class Program
{
static void Main()
{
string originalString = "This is a long string that needs to be truncated.";

// Method 1: Using Substring
string truncatedSubstring = originalString.Substring(0, Math.Min(originalString.Length, 20));
Console.WriteLine("Truncated using Substring: " + truncatedSubstring);

// Method 2: Using Remove
string truncatedRemove = originalString.Remove(20);
Console.WriteLine("Truncated using Remove: " + truncatedRemove);

// Method 3: Using StringBuilder
string truncatedStringBuilder = TruncateWithStringBuilder(originalString, 20);
Console.WriteLine("Truncated using StringBuilder: " + truncatedStringBuilder);
}
static string TruncateWithStringBuilder(string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
}

In this example:

1. We have an original string `originalString`.
2. Method 1 uses the `Substring` method to extract the first 20 characters of the string or all characters if the string is shorter than 20 characters.
3. Method 2 uses the `Remove` method to remove characters starting from the 20th index.
4. Method 3 demonstrates a custom function `TruncateWithStringBuilder` that truncates the string using a `StringBuilder`. This method is useful when you need to efficiently handle large strings.

You can choose any of these methods based on your preference and requirements.