Skip to main content

How to Truncate String in C#

 
How to Truncate  String in C# by Ziggy Rafiq

Overview

In today’s post, I am writing about one of the fundamental aspects of C# and as programmers, we should use this approach I have realised throughout my life as a software engineer that not everyone knows the most basic approaches or how to use them efficiently. Truncating a string in C# means reducing the length of a string to a specified number of characters, typically by removing characters from the end of the string. This is often done when a string is too long to be displayed or used in a specific context and needs to be shortened to fit. Ley says if we have a string that is 100 characters long, but we only want to display the first 50 characters, we will truncate the string to a length of 50. There are several ways to truncate a string in C#, including using the Substring method, StringBuilder, and LINQ.

A simple example of this is below, we're creating a longString variable with a long string value. We're also defining 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 up to the maximum length. The first parameter of the Substring method is the starting index of the substring, which is 0 in this case since we want to start from the beginning of the string. The second parameter is the length of the substring we want to get, which is maxLength in this case.

The resulting truncatedString variable will contain the first 20 characters of the original string. We then output this truncated string using Console.WriteLine. we can adjust the value of maxLength to truncate the string to a different length.

How to Truncate String in C# Code Example Overview by Ziggy Rafiq

StringBuilder

StringBuilder is a class in the System.Text namespace provides a more efficient way to manipulate strings than using the String class. The StringBuilder class allows you to append, insert, replace, or remove characters in a mutable string.

Using a StringBuilder can be more efficient than using the String class because String objects are immutable, which means that every time you modify a string, a new String object is created in memory. On the other hand, StringBuilder allows you to modify a single string in place, without creating new objects.

How to Truncate  String in C# using StringBuilder by Ziggy Rafiq




Substring Method

Substring is a method of the String class that allows you to extract a substring from a string.

The Substring method has two overloads. The first overload returns a substring that starts at the specified index and continues to the end of the string. The second overload returns a substring that starts at the specified index and has a specified length

How to Truncate  String in C# Code Example 03 by Ziggy Rafiq

In the code example below we're creating a string object and using the Substring method to extract a substring that starts at index 7 and has a length of 5. The resulting substring is "world", which we then output to the console.

How to Truncate  String in C# example 04 by Ziggy Rafiq

In another example of code below we're creating a string object and setting a maximum length for the truncated string. We're then using the Substring method to extract the first maxLength characters of the string starting from index 0. The resulting truncated string will have a length of 10, containing the characters "This is a ".

How to Truncate  String in C# 05 by Ziggy Rafiq


LINQ

LINQ stands for Language Integrated Query and is a feature of C# that allows you to query collections of objects using a syntax that is like SQL. LINQ provides a consistent way to work with data, regardless of its source, such as collections, databases, or XML documents.

LINQ is implemented using extension methods on collections, and it allows you to filter, sort, group, and transform data in a concise and readable way.

We can use LINQ to truncate a string by using the Take extension method. The Take method allows you to take a specified number of characters from the beginning of a string and returns a new string.

In the below code example, we're creating a string object and setting a maximum length for the truncated string. We're then using LINQ to take the first maxLength characters of the string using the Take method and 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, containing the characters "This is a ".

How to Truncate  String in C# Linq by Ziggy Rafiq

Summary

I have covered the technique of how to truncate a string refers to reducing the length of a string by removing characters from either its beginning or end. There are several ways to truncate a string in C#, including using the Substring method, the StringBuilder class, and LINQ's Take method. The Substring method allows you to extract a substring of a specified length from the beginning of a string. The StringBuilder class provides a more efficient way to modify strings than using the string class directly and can be used to remove characters from either end of a string. The Take method of LINQ can be used to extract a specified number of characters from the beginning of a string. When choosing a method to truncate a string, it is important to consider the size of the string, as well as the specific use case, as different methods may have different performance characteristics.

I have shared the source code for this post on my GitHub Repository, which is the following URL address- Click Here to Access Source Code For This Post.

 

Comments

Most Viewed Ziggy Rafiq Blog Posts

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6 Overview An Enum (Enumeration) is a group of constants that are read-only value types. By default, the first value of the Enum variable is 0 i.e. Here we will create an Enum of Priorities type with read-only values of Highest, Normal and Low. We will set the read-only values using an integer assigning a number next to the value. By default, the integer value will start with 0. Here we will be assigning the integer value next to the Enum value such as in the below example and we will use a comma (,) to separate the item in the list of Enum(Enumeration).  We create Enum by using the Enum keyword and then using class, interface, and abstract. The reason we use an Enum is to ensure we improve our application performance and improve application readability, and maintainability, and reduces the complexity of the application hence why if you take a look at the example below of Status (NotStarted, Started, Complete

A Complete Guide to Using GUIDs in C# with Code Examples

  Overview In this post, we are looking at GUIDs (Globally Unique Identifiers), which are widely used in C# for generating unique identifiers for objects, entities, and resources in a system. In this post, we'll explore the basics of GUIDs in C#, their advantages, and how to convert strings to GUIDs. In this post, we have used Guid Generator to create the GUID from the following URL Address https://guidgenerator.com/ What is GUID GUID (Globally Unique Identifier) in C# is a 128-bit value that is used to identify objects, entities, or resources in a unique manner across different systems and applications. It is also known as UUID (Universally Unique Identifier) in some other programming languages.   GUIDs are generated using a combination of unique factors such as the MAC address of the network adapter, the current time and date, and a random number. The resulting GUID is a string of 32 hexadecimal digits separated by hyphens, such as "b86f2096-237a-4059-8329-1bbcea72769b&

Primitives Data Types and None-Primitives Data Types in C# with Code Examples

  Overview I wrote this post to provide an explanation of primitive and non-primitive data types in C#. C# is a strongly typed programming language, where each variable and expression must have a specific data type. C# data types are categorized into two primary groups: primitive data types and non-primitive data types. Primitive data types are the simplest data types available in programming languages. They are typically pre-defined data types and can represent a single value, such as a boolean value, character, or integer. Examples of primitive data types include int, char, float, double, and boolean, which are common in programming languages like C++, C, and Java. Non-primitive data types are also referred to as composite data types or reference data types. They are constructed from primitive data types and are more complex than primitive data types. Non-primitive data types can hold multiple values and allow for the creation of more intricate data structures like tables, lists,