How to delete the last character in a string using StringBuilder in C#?
In C#, you can use the Remove method of StringBuilder to delete the last character. Here is the specific code:
StringBuilder sb = new StringBuilder("Hello World!");
sb.Remove(sb.Length - 1, 1);
In the code above, a StringBuilder object is first created and initialized to “Hello World!”. Then the Remove method is used to delete the last character. The Remove method takes two parameters, the first parameter is the starting index to be deleted, here it is passed as sb.Length – 1, which is the index of the last character in the string; the second parameter is the number of characters to be deleted, here it is passed as 1, indicating to delete only one character.
After deletion, the contents of the StringBuilder object become “Hello World”, with the last character “!” successfully removed.