c# - 替换字符串数组中的特定值

标签 c#

我这个程序的目标是创建一个用户可以在其中导航的网格。到目前为止,我已经创建了网格,但我一直不知道如何拥有它,以便在数组 string[3,6] 的任何位置我都可以用玩家符号“P”替换“-”之一,并且每次玩家移动控制台会打印玩家的位置。

EG。我希望玩家从字符串[2,5]开始,“-”将被替换为“P”,并且在玩家移动到[2,5]处的“-”后返回。

但我的主要关注点是找出如何用播放器替换数组的任意点。

希望一切都清楚

string[,] table = new string[3,6] { {"-","-","-","-","-","-"},
                                    {"-","-","-","-","-","-"},
                                    {"-","-","-","-","-","-"}}; 
int rows = grid.GetLength(0);
        int col = grid.GetLength(0);

        for (int x = 0; x < rows; x++) 
        {
            for (int y = 0; y < col; y++) 
            {
                Console.Write ("{0} ", grid [x, y]);
            }
            Console.Write (Environment.NewLine + Environment.NewLine);
        }

我尝试过使用 .Replace 但到目前为止还没有成功

最佳答案

我会做这样的事情:

private static int playerX, playerY;
public static void MovePlayer(int x, int y)
{
     table[playerX, playerY] = "-"; //Remove old position
     table[x, y] = "P"; //Update new position
     playerX = x; //Save current position
     playerY = y;

     UpdateGrid();
}

您所要做的就是将元素设置为“P”来更改它,没什么花哨的。

要更新网格,您有两个选择,要么重新绘制所有内容,要么设置光标位置并更改字符。

示例:

SetCursorPosition(playerX, playerY);
Console.Write("-");
SetCursorPosition(x, y);
Console.Write("P");

或者,使用您现在拥有的代码再次调用它来重写所有内容。

关于c# - 替换字符串数组中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23187940/

相关文章:

c# - 在 Entity Framework Core 中使用 Fluent API 编写范围数据注释

c# - 将结构从 C# 传递到非托管代码

c# - 如何使用 C# 将月或日转换为 2 位数字字符串

c# - 我可以使用 WCF 在 2 个 Windows 服务之间进行通信(发送消息)吗?

c# - 为什么 PCL NuGet 包无法定位 Xamarin 平台?

c# - C# 子类中的 protected 属性是否应该隐藏对父类公共(public)属性的访问?

c# - ASP.NET Identity 不是 "saving"更新声明

c# - Entity Framework : Dynamically generate multiple OR condition on JOIN

C# 错误帮助 - "ExecuteNonQuery: CommandText property has not been initialized "

c# - 是什么导致了这个 MySql.Data.MySqlClient.MySqlException? C#