C# quickest way to shift array

前端 未结 20 1311
礼貌的吻别
礼貌的吻别 2020-12-01 01:35

How can I quickly shift all the items in an array one to the left, padding the end with null?

For example, [0,1,2,3,4,5,6] would become [1,2,3,4,5,6,null]

Ed

20条回答
  •  悲&欢浪女
    2020-12-01 02:23

    See C# code below to remove space from string. That shift character in array. Performance is O(n). No other array is used. So no extra memory either.

        static void Main(string[] args)
        {
            string strIn = System.Console.ReadLine();
    
            char[] chraryIn = strIn.ToCharArray();
    
            int iShift = 0;
            char chrTemp;
            for (int i = 0; i < chraryIn.Length; ++i)
            {
                if (i > 0)
                {
                    chrTemp = chraryIn[i];
                    chraryIn[i - iShift] = chrTemp;
                    chraryIn[i] = chraryIn[i - iShift];
                }
                if (chraryIn[i] == ' ') iShift++;
                if (i >= chraryIn.Length - 1 - iShift) chraryIn[i] = ' ';
            }
           System.Console.WriteLine(new string(chraryIn));
           System.Console.Read();
        }
    

提交回复
热议问题