25

Is there any function in C# that remove from string on specific index, for example

string s = "This is string";

s.RemoveAt(2);

s is now "Ths is string"

???

5 Answers 5

33
string s = "This is string";
s = s.Remove(2, 1);

Output : Ths is string

1st parameter is the starting index from which you want to remove character and 2nd parameter is the number of character you want to remove

9

As many others have said, there's a Remove method. What the other posts haven't explained is that strings in C# are immutable -- you cannot change them.

When you call Remove, it actually returns a new string; it does not modify the existing string. You'll need to make sure to grab the output of Remove and assign it to a variable or return it... just calling Remove on its own does not change the string.

3

You can write your on extension for this using the Remove method:

public static class MyStringExtensions
{
     public static string RemoveAt(this string s, int index)
     {
         return s.Remove(index, 1);
     }
}

usage:

string s = "This is string";
s = s.RemoveAt(2);
1

You could use Regular Expressions also.

Console.WriteLine(Regex.Replace("This is string", @"(?<=^.{2}).", ""));

This would remove the third character from the start.

DEMO

3
  • 1
    A regex is overkill for this situation. Dec 27, 2014 at 16:41
  • 1
    yep agree regex is an overkill. I think op is asking for possibilities. Dec 27, 2014 at 16:44
  • 2
    ...the good thing is, this works for almost every programming language I think. I didn't know it so cool that you posted this possiblity too.
    – t3chb0t
    Dec 27, 2014 at 17:31
0

There is the String.Remove method:

s = s.Remove(2, 1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.