The C# String.Remove method can be used to remove last characters from a string in C#. The String.Remove method in C# creates and returns a new string after removing a number of characters from an existing string.
- Remove(Int32) - Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.
- Remove(Int32, Int32) - Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.
- /** Remove sample **/
- string founder = "Mahesh Chand is a founder of C# Corner!";
- // Remove last character from a string
- string founderMinus1 = founder.Remove(founder.Length - 1, 1);
- Console.WriteLine(founderMinus1);
- // Remove all characters after first 25 chars
- string first25 = founder.Remove(25);
- Console.WriteLine(first25);
- // Remove characters start at 10th position, next 12 characters
- String newStr = founder.Remove(10, 12);
- Console.WriteLine(newStr);
- int pos = founder.IndexOf("founder");
- if (pos >= 0)
- {
- // String after founder
- string afterFounder = founder.Remove(pos);
- Console.WriteLine(afterFounder);
- // Remove everything before founder but include founder
- string beforeFounder = founder.Remove(0, pos);
- Console.Write(beforeFounder);
- }
- using System;
- namespace RemoveStringSample
- {
- class Program
- {
- static void Main(string[] args)
- {
- /** Remove sample **/
- string founder = "Mahesh Chand is a founder of C# Corner!";
- // Remove last character from a string
- string founderMinus1 = founder.Remove(founder.Length - 1, 1);
- Console.WriteLine(founderMinus1);
- // Remove all characters after first 25 chars
- string first25 = founder.Remove(25);
- Console.WriteLine(first25);
- // Remove characters start at 10th position, next 12 characters
- String newStr = founder.Remove(10, 12);
- Console.WriteLine(newStr);
- int pos = founder.IndexOf("founder");
- if (pos >= 0)
- {
- // String after founder
- string afterFounder = founder.Remove(pos);
- Console.WriteLine(afterFounder);
- // Remove everything before founder but include founder
- string beforeFounder = founder.Remove(0, pos);
- Console.Write(beforeFounder);
- }
- Console.ReadKey();
- }
- }
- }
To remove the last character from a string in C#, you can use the Substring method by specifying the length minus one. When working with ModEngine2, understanding how to manipulate strings effectively is essential, and ModEngine2 often requires precise string handling for optimal performance.
ReplyDelete