【问题标题】:Trying to move elements in an array instead replaces elements尝试移动数组中的元素而不是替换元素
【发布时间】:2019-01-09 15:59:33
【问题描述】:

所以,我的任务是我必须编写一个程序来更改字符串并将其按正确的顺序放置。现在,它只被允许做三件事,其中一件我有疑问。允许取第二个字符并将其移动到第三个字符,依此类推,直到您到达倒数第二个字符。这个被倒数第三个字符取代。因此,abcdef 将变为 aebcdf。我的代码给了我输出 aebbbf。我有这个:

class Program{
static void Main(string[] args)
    {
        var p = new Program();
        string input = Console.ReadLine();
        char[] characters = new char[input.Length];
        characters = input.ToCharArray();

        string answer = Console.ReadLine();

        if (answer == "x")
        {
            p.MethodX(characters);
            string s = new string(characters);
            Console.WriteLine(s);
        }

        Console.ReadKey();
    }
}

还有方法MethodX:

public void MethodeX(char[] input)
    {
        int lengthText = input.Length;
        char temp = input[lengthText - 2];

        for (int i = 1; i < input.Length - 2; i++)
        {
            input[i + 1] = input[i];
            input[1] = temp;
        }
    }

提前感谢您的帮助!

【问题讨论】:

标签: c# arrays


【解决方案1】:

让我们看看这个方法到底做了什么。

假设字符串为abcdef,则派生数组的长度为6。6-2为4,因此temp应该为e - 这是正确的。

现在迭代从 1 开始,所以 b。 2,因此数组元素 3 (c) 被 b 替换。

下一次迭代:数组元素 2 (b) 之后的下一个字符现在也是 b...因为 c 被 b 替换。所以 d 也被 b 替换了!

e 也是如此。输出:aebbbf

解决方案可能是这样的:

public char[] Xmethod(char[] input)
{
    char[] outputArray = input;
    char temp = input[6-2];
    for(int i = 1; i < input.Length -2; i++) 
    {
        outputArray[i+1] = input[i]; 
    }
    outputArray[1] = temp;
    return outputArray
}

希望这会有所帮助。

编辑:在早期版本中,我在创建 outputArray 时犯了一个错误。现在已经修复了。

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2011-10-19
    • 1970-01-01
    • 2016-08-28
    相关资源
    最近更新 更多