Languages
[Edit]
EN

C# / .NET - remove last 3 characters from string

0 points
Created by:
Marcino
360

In this article, we would like to show you how to remove the last 3 characters from the string in C# / .NET.

Quick solution:

string text = "ABCDE";

string result = text[..^3];
Console.WriteLine(result);  // AB

 

Practical examples

1. Using String Substring() method

In this example, we use String Substring() method to create a new result substring from the text string without the last 3 characters.

Syntax:

Substring (int startIndex, int length);

Note:

If length is not given, substring will be done from startIndex to the end of the text.

Practical example:

using System;

public class StringUtils
{
    public static void Main(string[] args)
    {
        string text = "ABCDE";

        string result = text.Substring(0, text.Length - 3);
        Console.WriteLine(result);  // AB
    }
}

Output:

AB

2. Using index from end ^ and range operator ..

The range operator .. is used to make a slice of the collection.

Practical example:

using System;

public class StringUtils
{
    public static void Main(string[] args)
    {
        string text = "ABCDE";

        string result = text[..^3]; // text[Range.EndAt(new Index(3, fromEnd: true))]
        Console.WriteLine(result);  // ABC
    }
}

Output:

AB

3. Using String Remove() method

Syntax:

Remove (int startIndex, int count);

Practical example:

using System;

public class StringUtils
{
    public static void Main(string[] args)
    {
        string text = "ABCDE";

        // Remove last 3 characters
        string result = text.Remove(text.Length - 3);

        Console.WriteLine(result);
    }
}

Output:

AB

Reference

  1. Substring() method - .NET Docs
  2. Range operator - .NET Docs
  3. String.Remove Method - .NET Docs 

C# / .NET - String (popular problems)

C# / .NET - remove last 3 characters from string
Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join