How To Truncate String In C#

Overview

Today's post discusses a fundamental aspect of C# programming that is often overlooked. Truncating a string in C# involves reducing its length to fit a specific context or display. This process typically involves removing characters from the end of the string. There are several ways to truncate a string in C#, including the Substring method, StringBuilder, and LINQ.

This post demonstrates a simple example of using the Substring method to truncate a string. We define a longString variable with a long string value and a maxLength variable with a value of 20, which is the maximum length we want the truncated string to be. We then use the Substring method to get a portion of the original string to the maximum length. The resulting truncatedString variable will contain the first 20 characters of the original string, which we output using Console.WriteLine. By adjusting the value of maxLength, we can truncate the string to a different length.

string longString = "This is a simple long string that need to be truncated";
int maxLength = 20;
string truncatedString = longString.Substring(0, maxLength);
Console.WriteLine(truncatedString);
Console.ReadLine();

StringBuilder in C#

The StringBuilder is a class within the System.Text namespace that offers a more efficient approach to manipulating strings compared to the String class. With the StringBuilder class, you can modify a mutable string by appending, inserting, replacing or removing characters.

Using the StringBuilder class can be advantageous over the String class since String objects are immutable. This means that a new String object is created in memory any time you modify a string. In contrast, the StringBuilder class allows you to modify a single string in situ without generating new objects.

StringBuilder sb = new StringBuilder();
sb.Append("This is ");
sb.Append("a string ");
sb.Append("built using .Net System.Text String Builder ");
sb.Append("by Ziggy Rafiq ");

string result = sb.ToString();
Console.WriteLine(result);
Console.ReadLine();

Substring Method in C#

The String class provides a method called Substring, which enables you to extract a portion of a string.

There are two overloads of the Substring method. The first overload retrieves a substring that starts from a specified index and extends till the end of the original string. The second overload returns a substring starting at a specified index and has a specified length.

string Substring(int startIndex);
string Substring(int startIndex, int length);

In the following code above example, we instantiate a string object and use the Substring method to retrieve a substring beginning at index 7 with a length of 5. The resultant substring, "world", is subsequently printed to the console.

string helloWorld = "Hello, World!";
string subStringHelloWorld = helloWorld.Substring(7, 5);

Console.WriteLine(subStringHelloWorld);

In a separate code instance presented below, we initialize a string object and establish the maximum length of the truncated string. Then, using the Substring method, we extract the initial maxLength characters from the string beginning at index 0. The resulting truncated string will have a length of 10 and comprise the characters "This is a".

string longString = "This is a simple long string that need to be truncated";
int maxLength = 20;
string subStringLongString = longString.Substring(0, maxLength);
Console.WriteLine(subStringLongString);

LINQ

LINQ, which stands for Language Integrated Query, is a C# feature that enables querying collections of objects utilizing a syntax reminiscent of SQL. This functionality provides a consistent approach to working with data from various sources, including databases, collections, or XML documents.

To accomplish this, LINQ utilizes extension methods on collections, facilitating filtering, sorting, grouping, and data transformation succinctly and comprehensibly.

One way to truncate a string using LINQ is by employing the Take extension method. The Take method retrieves a specified number of characters from the beginning of a string, generating a new string.

In the code example below, we initialize a string object and define the maximum length for the truncated string. Subsequently, we leverage LINQ to take the first maxLength characters of the string using the Take method. We create a new string from the resulting array using the ToArray and string constructor methods. The resulting truncated string will have a length of 10, including the characters "This is a ".

string longString = "This is a simple long string that need to be truncated";
int maxLength = 10;
string linqString = new string(longString.Take(maxLength).ToArray());
Console.WriteLine(linqString);

Summary

In this discussion, I have covered various techniques for truncating a string, which refers to shortening a string by eliminating characters from its start or end. Multiple methods are available in C# for truncating a string, such as the Substring method, the StringBuilder class, and LINQ's Take method.

The Substring method enables the extraction of a substring of a defined length from the beginning of a string. The StringBuilder class offers a more efficient approach to modifying strings than the string class directly and can eliminate characters from either end of a string. The Take method of LINQ can extract a specified number of characters from the beginning of a string.

While deciding on a truncation technique, it's crucial to consider the string's size and the specific use case, as different methods may have varying performance characteristics.

I have shared the source code for this post on my GitHub Repository, which is the following URL address-  https://github.com/ziggyrafiq/Truncate-String

Please do not forget to follow me on LinkedIn https://www.linkedin.com/in/ziggyrafiq/ and click the like button if you have found this article useful/helpful.


Similar Articles
Capgemini
Capgemini is a global leader in consulting, technology services, and digital transformation.