如何正确将二维数组中的随机0、1替换为指定符号
现有代码错误说明
你的代码存在以下核心问题导致功能无法实现:
- 存储类型不匹配:你定义的是
int[,]整数类型数组,无法存储_、*这类字符类型数据 - 替换逻辑错误:你写的
if (i == 0)、if (j == 1)判断只会处理第一行、第二列的元素,和全局替换0、1的需求完全不符 - Regex使用完全错误:Regex是用于字符串正则匹配的工具,不适合做单值替换,且你调用Replace方法时参数顺序颠倒,也没有接收替换返回结果,原数组不会产生任何变更
- 输出内容为原始整数:你最终直接输出的是int类型的0和1,自然看不到替换后的字符效果
正确实现方案
这里提供两种可选实现,可根据你的需求选择:
方案1:保留原int数组,仅输出时做映射(不需要修改原数组结构,性能更好)
Console.Write("Enter the width of the field: "); int q = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the length of the field: "); int w = Convert.ToInt32(Console.ReadLine()); int[,] myArray = new int[q, w]; Random rand = new Random(); for (int i = 0; i < q; i++) { for (int j = 0; j < w; j++) { myArray[i, j] = rand.Next(2); // 输出时直接做值映射 char outputChar = myArray[i, j] == 0 ? '_' : '*'; Console.Write(outputChar); } Console.WriteLine(); }
方案2:直接存储替换后的字符到数组(适合需要后续使用替换后内容的场景)
Console.Write("Enter the width of the field: "); int q = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the length of the field: "); int w = Convert.ToInt32(Console.ReadLine()); char[,] myArray = new char[q, w]; Random rand = new Random(); for (int i = 0; i < q; i++) { for (int j = 0; j < w; j++) { int randomVal = rand.Next(2); myArray[i, j] = randomVal == 0 ? '_' : '*'; Console.Write(myArray[i, j]); } Console.WriteLine(); }
内容的提问来源于stack exchange,提问作者foder.
相关产品推荐
相关产品推荐

