C# remove first or last character from string

Lionsure 2020-07-20 Original by the website

In the process of program development, removing and inserting characters are common operations; different languages have different operating methods. The following is the implementation code of C# to remove the first or last character:

 

1. Remove first character from string C#

/// <summary>
       /// Remove first character from string C#
       /// </summary>
       /// <param name="str">String to remove the first character</param>
       /// <returns>The string after the first character is removed</returns>

       public string RemoveFirstString(string str)
       {
              str = str.Substring(1);
              return str;
       }

Call:

string s = "1a,b,c,d,e";

RemoveFirstString(s);//Output: a,b,c,d,e

 

2. C# remove last character from string

/// <summary>
       /// C# remove last character from string
       /// </summary>
       /// <param name="str">String with the last character to be removed</param>
       /// <returns>String after removing the last character</returns>

       public string RemoveLastString(string str)
       {
              str = str.Substring(0, str.Length - 1);
              return str;
       }

Call:

string s = "a,b,c,d,e,";

RemoveLastString(s);//Output: a,b,c,d,e

The above two methods have been tested and no problems were found. You can call them directly; of course, if you have better methods, you can ignore them.