c# - 从字符串中删除最后 X 个特定字符

标签 c#

删除字符串中最后两个“0”以使结果变为 000110100111 的最快方法是什么?

string text1 = "00011010001101";

最佳答案

这个片段应该做:

 string text1 = "00011010001101";

 int count = 2;

 string result = text1;
 for (int i = 0; i < count; i++)
 {
      result = result.Remove(result.LastIndexOf("0"), 1);
 }
PS。 LINQ方式:

var result = Enumerable.Repeat("0", count)
            .Aggregate(text1, (text, charToRemove) => text.Remove(text.LastIndexOf(charToRemove), 1));

Enumerable.Repeat 的第一个参数是要删除的子字符串,第二个参数告诉它应该删除多少次。

关于c# - 从字符串中删除最后 X 个特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20827973/

相关文章:

c# - 为什么大多数时候只能向前遍历?

c# - 使用 C# 从服务器读取数据库名称

c# - 运行时的 Autofac 通用服务解析

c# - .NET 2.0 中的等效任务

c# - ListView与DataTable绑定(bind),删除行后不更新

c# - 如何比较可为空的 int 和 int

c# - 在Windows调音台中读取音量值

c# - 如何编写使用 HttpContext 的服务器端单元测试?

c# - System.Internal(x64 上的 .net 4.0)中 _HACK 方法的目的是什么

c# - linq 中的子查询和分组依据