删除字符串中最后两个“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/