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

时间:2013-12-29 17:22:59

标签: c#

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

string text1 = "00011010001101";

2 个答案:

答案 0 :(得分:4)

此代码段应该:

 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的第一个参数是要删除的子字符串,第二个参数表示应删除它的次数。

答案 1 :(得分:0)

我认为手动执行此操作的最快方式是:

string text1 = "00011010001101";
int count=0;
for (int i = text1.Length-1; i>=0; i--)
{
    if (text1[i] == '0')
    {
        text1 = text1.Remove(i, 1);
        count++;
    }

    if (count == 2)
        break;
}

持续时间为20个刻度。使用LastIndexOf()搜索的另一种方法需要53个滴答。

相关问题