连续使用相同的字符列表,我无法删除所有字符列表

时间:2018-07-22 10:09:44

标签: c#

当我要删除此代码列表中“ o”的特定字符时,它会删除其中一些字符,而不会删除。我的意思是,当我调试它时,结果是(Roazooooor)。我想删除所有的“ o”字符而不是其中的一半 并且当我调试它时,我希望它给我(剃刀)不带“ o”。

    namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Rooazoooooooooor";
            var nameChar = new List<char>();
            nameChar.AddRange(name);
            for (int i = 0; i < nameChar.Count; i++)
            {
                if (nameChar[i] == 'o')
                    nameChar.Remove(nameChar[i]);
                Console.Write(nameChar[i]);

            }
            Console.WriteLine();
        }
    }
}

this is what happen when I debug it

2 个答案:

答案 0 :(得分:3)

问题是,当您删除一个项目时,您将移至下一个索引,即使您将该项目之后的所有内容都随机排序了。

在这种情况下,最简单的选择是先使用string.Replace

name = name.Replace("o", "");
var nameChar = new List<char>(name);

或者您可以保留现有代码并使用:

while (nameChar.Remove('o')) ;

nameChar.RemoveAll(c => c == 'o');

所有这些都会为您提供一个不含任何'o'元素的列表。

要在当前代码中进行绝对最小的更改,可以将循环更改为:

for (int i = 0; i < nameChar.Count; i++)
{
    if (nameChar[i] == 'o')
    {
        // After removing the element at index i,
        // we want to try index i again, so decrement
        // and continue without printing.
        nameChar.Remove(nameChar[i]);
        i--;
        continue;
    }
    Console.Write(nameChar[i]);
}

答案 1 :(得分:0)

在您的情况下是否有必要使用List?如果没有,那么:

class Program
{
    static void Main(string[] args)
    {
        string name = "Rooazoooooooooor";
        string resultName = string.Empty;
        foreach (var currentChar in name)
        {
            if (currentChar != 'o')
                resultName += currentChar;
        }
        Console.Write(resultName);
        Console.ReadKey();
    }
}

`