Languages
[Edit]
EN

C# / .NET - remove first n characters from string

0 points
Created by:
Marcino
720

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

Quick solution:

string text = "ABCD";
int n = 3;
string result = text[n..];

Console.WriteLine(result);  // D

 

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 first n 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";

        int n = 3;
        string result = text.Substring(n);
        Console.WriteLine(result);  // DE
    }
}

Output:

DE

2. Using 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";

        int n = 3;
        string result = text[n..];  // text[Range.StartAt(n)]
        Console.WriteLine(result);  // DE
    }
}

Output:

DE

3. Using StringBuilder Remove() method

In this example, we create sb StringBuilder object from the text string, then we use Remove() method on the sb to delete the first 3 characters. 

Syntax:

Remove(int startIndex, int length)

Practical example:

using System;
using System.Text;

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

        // Create StringBuilder object
        StringBuilder sb = new(text);

        // Remove first n characters
        int n = 3;
        sb.Remove(0, n);

        Console.WriteLine(sb);
    }
}

Output:

DE

Reference

  1. Substring() method - .NET Docs
  2. Range operator - .NET Docs
  3. StringBuilder Class - .NET Docs 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# / .NET - String (popular problems)

C# / .NET - remove first n 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