Removing char in string from specific index

前端 未结 5 933
情话喂你
情话喂你 2021-02-18 14: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 \"Th

相关标签:
5条回答
  • 2021-02-18 14:27
    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

    0 讨论(0)
  • 2021-02-18 14:31

    There is the String.Remove method:

    s = s.Remove(2, 1);
    
    0 讨论(0)
  • 2021-02-18 14:33

    You could use Regular Expressions also.

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

    This would remove the third character from the start.

    DEMO

    0 讨论(0)
  • 2021-02-18 14:43

    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);
    
    0 讨论(0)
  • 2021-02-18 14:47

    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.

    0 讨论(0)
提交回复
热议问题