EN
C# / .NET - remove first n characters from string
0 points
In this article, we would like to show you how to remove the first n characters from the string in C# / .NET.
Quick solution:
xxxxxxxxxx
1
string text = "ABCD";
2
int n = 3;
3
string result = text[n..];
4
5
Console.WriteLine(result); // D
In this example, we use String Substring()
method to create a new result
substring from the text
string without the first n
characters.
Syntax:
xxxxxxxxxx
1
Substring(int startIndex, int length);
Note:
If
length
is not given, substring will be done fromstartIndex
to the end of the text.
Practical example:
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
string text = "ABCDE";
8
9
int n = 3;
10
string result = text.Substring(n);
11
Console.WriteLine(result); // DE
12
}
13
}
Output:
xxxxxxxxxx
1
DE
The range operator ..
is used to make a slice of the collection.
Practical example:
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
string text = "ABCDE";
8
9
int n = 3;
10
string result = text[n..]; // text[Range.StartAt(n)]
11
Console.WriteLine(result); // DE
12
}
13
}
Output:
xxxxxxxxxx
1
DE
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:
xxxxxxxxxx
1
Remove(int startIndex, int length)
Practical example:
xxxxxxxxxx
1
using System;
2
using System.Text;
3
4
public class StringUtils
5
{
6
public static void Main(string[] args)
7
{
8
string text = "ABCDE";
9
10
// Create StringBuilder object
11
StringBuilder sb = new(text);
12
13
// Remove first n characters
14
int n = 3;
15
sb.Remove(0, n);
16
17
Console.WriteLine(sb);
18
}
19
}
Output:
xxxxxxxxxx
1
DE