The string type does not provide a Truncate method. We must use a conditional expression and either Substring or Remove.
using System;
class Program
{
static void Main()
{
string result = StringTool.Truncate(
"Carrot", 3);
string result2 = StringTool.Truncate2(
"Carrot", 3);
Console.WriteLine(result);
Console.WriteLine(result2);
result = StringTool.Truncate(
"Computer", 20);
result2 = StringTool.Truncate2(
"Computer", 20);
Console.WriteLine(result);
Console.WriteLine(result2);
}
}
/// <summary>
/// Custom string utility methods.
/// </summary>
public static class StringTool
{
/// <summary>
/// Get a substring of the first N characters.
/// </summary>
public static string Truncate(string source, int length)
{
if (source.Length > length)
{
source = source.Substring(0, length);
}
return source;
}
/// <summary>
/// Get a substring of the first N characters. [Slow]
/// </summary>
public static string Truncate2(string source, int length)
{
return source.Substring(0, Math.Min(length, source.Length));
}
}
Car
Car
Computer
Computer