Use the StringBuilder.Remove function in C# to delete the specified part of the string
In C#, the StringBuilder class is a mutable string type that allows We modify and operate strings. The Remove function of StringBuilder provides a convenient way to delete the specified part of the string.
The usage of the StringBuilder.Remove function is as follows:
public StringBuilder Remove(int startIndex, int length);
Among them, startIndex represents the starting position to be deleted, and length represents the number of characters to be deleted.
The following uses a specific example to demonstrate how to use the StringBuilder.Remove function to delete a specified part of a string.
using System; using System.Text; class Program { static void Main(string[] args) { StringBuilder sb = new StringBuilder("Hello, World!"); Console.WriteLine("原始字符串:{0}", sb); // 删除字符串中的指定部分 sb.Remove(7, 7); // 删除", World!" Console.WriteLine("删除指定部分后的字符串:{0}", sb); Console.ReadLine(); } }
In the above example, we first created a StringBuilder object and assigned the string "Hello, World!" to it. Then by calling the Remove function of StringBuilder, specify the starting position to be deleted as 7 (that is, the position of ","), and the number of characters to be deleted as 7 (that is, the length of ", World!"), thereby deleting the contents of the string. designated part. Finally, we output the original string and the result after deleting the specified part through the Console.WriteLine function.
Run the above code, the following results will be output:
原始字符串:Hello, World! 删除指定部分后的字符串:Hello
Through this simple example, you can see how to use the StringBuilder.Remove function in C# to delete the specified string part. In practical applications, you can use this function flexibly to modify and manipulate strings as needed.
The above is the detailed content of Remove a specified part of a string using the StringBuilder.Remove function in C#. For more information, please follow other related articles on the PHP Chinese website!