C#
string manipulation
programming
coding tips
software development

Remove last characters from a string in C. An elegant way?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C#, the most elegant way to remove characters from the end of a string depends on which language version you are using and how defensive the code needs to be. Because strings are immutable, every solution returns a new string rather than editing the existing one in place. For most cases, Substring, Remove, or the newer range syntax are the right tools.

Use Substring in Any C# Version

The classic approach is:

csharp
1string text = "abcdef";
2string result = text.Substring(0, text.Length - 2);
3
4Console.WriteLine(result); // abcd

This says:

  • start at index 0
  • keep everything up to Length - count

It is simple and widely supported, which makes it a solid default if you are not targeting the newest C# features.

Use Remove for a Direct Intent

Remove can read a little more clearly because it expresses the operation as "remove from this index to the end."

csharp
1string text = "abcdef";
2string result = text.Remove(text.Length - 2);
3
4Console.WriteLine(result); // abcd

For many developers, this is the most readable option because it directly describes the removal point rather than the remaining slice length.

Modern C# Range Syntax

If you are on a newer C# version, range syntax is concise and expressive:

csharp
1string text = "abcdef";
2string result = text[..^2];
3
4Console.WriteLine(result); // abcd

Here:

  • '.. means a range'
  • '^2 means "two positions from the end"'

So [..^2] means "take everything up to, but not including, the last two characters."

This is often the nicest syntax when your team is already comfortable with ranges.

Write a Safe Helper Function

If the number of characters to remove comes from input, wrap the logic so edge cases are handled consistently.

csharp
1public static string RemoveLastCharacters(string value, int count)
2{
3    if (value == null)
4        throw new ArgumentNullException(nameof(value));
5
6    if (count < 0)
7        throw new ArgumentOutOfRangeException(nameof(count));
8
9    if (count >= value.Length)
10        return string.Empty;
11
12    return value[..^count];
13}

Example:

csharp
Console.WriteLine(RemoveLastCharacters("abcdef", 2)); // abcd
Console.WriteLine(RemoveLastCharacters("ab", 2));     // empty string

Encapsulating the behavior is useful if multiple parts of the codebase need the same rules.

Handle Special Cases Deliberately

The edge cases matter:

  • removing 0 characters should usually return the original string
  • removing all characters should usually return ""
  • negative counts should throw or be rejected

If you use Substring(0, text.Length - count) without guards, invalid counts can trigger exceptions unexpectedly.

A more complete helper can preserve the zero-removal case explicitly:

csharp
1public static string TrimEndCount(string value, int count)
2{
3    if (value == null)
4        throw new ArgumentNullException(nameof(value));
5
6    if (count < 0)
7        throw new ArgumentOutOfRangeException(nameof(count));
8
9    if (count == 0)
10        return value;
11
12    if (count >= value.Length)
13        return string.Empty;
14
15    return value.Remove(value.Length - count);
16}

When Not to Use Regex

Some developers reach for regular expressions for almost every string task, but removing a known number of trailing characters is not a regex problem. Plain slicing or Remove is simpler, faster to read, and easier to maintain.

Regex starts to make sense only when the rule is pattern-based, such as removing all trailing digits or whitespace. For a fixed count, normal string methods are the better choice.

Common Pitfalls

The most common issue is forgetting that strings are immutable. Calling Substring, Remove, or range syntax does not change the original value unless you assign the result.

Another problem is not guarding against a count greater than the string length. That can cause ArgumentOutOfRangeException.

Developers also sometimes use range syntax like [..^count] without handling count == 0, which can be awkward if the semantics are not defined in one place.

Finally, make sure the code is actually C#, not C. The article title says C, but the methods discussed here are from C#’s string API.

Summary

  • 'Substring, Remove, and range syntax are the main C# ways to remove trailing characters.'
  • 'Remove(text.Length - count) often reads most directly.'
  • '[..^count] is concise in modern C#.'
  • Wrap the logic in a helper when input counts may be invalid or reused widely.
  • Handle zero, full-length, and negative counts explicitly for robust behavior.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.