Languages
[Edit]
EN

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

0 points
Created by:
Palusbug
365

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

Quick solution:

string text = "ABCD";

string result = text.Substring(2);
Console.WriteLine(result);  // CD

 

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 2 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 = "ABCD";

        string result = text.Substring(2);
        Console.WriteLine(result);  // CD
    }
}

Output:

CD

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

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

        // Remove first 2 characters
        sb.Remove(0, 2);

        Console.WriteLine(sb);
    }
}

Output:

CD

C# / .NET - String (popular problems)

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