C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
We truncate a string so that it has a substring of the first specified number of letters. This is useful for text in databases or in user interfaces where space is limited.
Example. First, the string type does not provide a Truncate method. We must use a conditional expression and either Substring or Remove. Looking in IL Disassembler, Remove calls into Substring. So these custom methods directly call Substring.
C# program that truncates strings using System; class Program { static void Main() { Console.WriteLine(StringTool.Truncate("Carrot", 3)); // Write first 3 characters Console.WriteLine(StringTool.Truncate2("Carrot", 3)); // Same Console.WriteLine(StringTool.Truncate("Wagstaff", 20)); // Write all characters Console.WriteLine(StringTool.Truncate2("Wagstaff", 20)); // Same } } /// <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)); } } Output Car Car Wagstaff Wagstaff
The first truncation method, Truncate, tests the length of the source string to see if it needs any processing. If the source is longer than the max length, we call Substring to get the first N characters. This copies the string.
The second, Truncate2, uses a nested Math.Min expression in a Substring call. In this method, the Substring method is always entered. This is inefficient if no processing is necessary.
Info: By always entering the Substring method, we may create string copies that are not needed.
Performance. I wanted to know if avoiding the Substring call entirely in cases where it is not needed would have an impact on performance. And I found using the if-statement before calling Substring is faster.
Result: The Truncate with an if-statement finished the test in 2753 ms, while the Truncate with Math.Min completed the test in 3463 ms.
Benchmarked code: C# // This code was in one loop: string a = StringTool.Truncate("Carrot", 3); string b = StringTool.Truncate("Carrot", 10); // This code was in another loop: string a = StringTool.Truncate2("Carrot", 3); string b = StringTool.Truncate2("Carrot", 10); Notes on benchmark 100000000 iterations of the two loops. Standard benchmark loops were used. Truncate with if: 2753 ms [faster] Truncate with Math.Min: 3463 ms
Summary. Here we saw two implementations of string Truncate. We validated that they have correct results. Also, we saw how avoiding the Substring call when it is not necessary is substantially faster.