Languages
[Edit]
EN

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

0 points
Created by:
Dirask Admin - Marwin
1430

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

Quick solution:

string originalString = "This is your text";
string result = originalString.Remove(originalString.Length - 3);

Console.WriteLine( result ); // This is your t

 

Practical Examples

1. Remove chars with String.Substring()

using System;

public class Program
{
    static string RemoveChars(string originalString, int charsToRemoveCounter)
    {
        return originalString.Substring(0, originalString.Length - charsToRemoveCounter);
    }

    public static void Main(string[] args)
    {
        string string1 = "This is your text";
        string string2 = "Another string";

        Console.WriteLine( RemoveChars( string1, 2) ); // This is your te
        Console.WriteLine( RemoveChars( string2, 4) ); // Another st
    }
}

Output:

This is your te
Another st

2. Remove char with String.Remove()

using System;

public class Program
{
    static string RemoveChars(string originalString, int charsToRemoveCounter )
    {
        return originalString.Remove( originalString.Length - charsToRemoveCounter );
    }

    public static void Main(string[] args)
    {
        string string1 = "This is your text";
        string string2 = "Another string";

        Console.WriteLine( RemoveChars( string1, 2) ); // This is your te
        Console.WriteLine( RemoveChars( string2, 4) ); // Another st
    }
}

Output:

This is your te
Another st

C# / .NET - String (popular problems)

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