You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#二维数组中存储元素:下一行以上一行末尾元素开头

实现循环移位的n×n字符矩阵

要实现你需要的循环移位矩阵,核心是让第i行的内容是原字符串循环右移i位的结果。以下是两种直观的实现思路和对应的C#代码:

思路1:通过索引计算直接赋值

对于第i行的第j个字符,我们可以通过取模运算找到它在原字符串数组中的对应位置:

  • 原字符串长度为n,第i行相当于把原字符串的末尾i个字符移到开头
  • 第i行第j个字符的原索引为:(j - i + n) % n(加n是为了避免负数取模的问题)

修改你现有代码的赋值逻辑即可:

string test = "Hello";
int n = test.Length;
char[] charArr = test.ToCharArray();
char[][] matrix = new char[n][];

// 填充矩阵
for (int i = 0; i < n; i++)
{
    matrix[i] = new char[n];
    for (int j = 0; j < n; j++)
    {
        // 计算当前字符在原数组中的索引
        int originalIndex = (j - i + n) % n;
        matrix[i][j] = charArr[originalIndex];
    }
}

// 打印矩阵
for (int m = 0; m < matrix.Length; m++)
{
    Console.WriteLine(new string(matrix[m])); // 简化打印:char数组直接转字符串
}

思路2:利用字符串拼接截取(更简洁)

把原字符串拼接成自身的两倍(比如"Hello"变成"HelloHello"),然后每行从拼接后的字符串中截取长度为n的子串:

  • 第i行对应的起始位置是 n - i,截取长度为n的子串就是循环右移i位的结果

代码示例:

string test = "Hello";
int n = test.Length;
string doubledStr = test + test; // 拼接成"HelloHello"
char[][] matrix = new char[n][];

// 填充矩阵
for (int i = 0; i < n; i++)
{
    // 截取对应子串并转char数组
    string rowStr = doubledStr.Substring(n - i, n);
    matrix[i] = rowStr.ToCharArray();
}

// 打印矩阵
foreach (var row in matrix)
{
    Console.WriteLine(new string(row));
}

关键说明

  • 两种方法都能达到目标:第一种更底层,适合理解索引操作;第二种利用字符串API,代码更简洁易读
  • 取模运算%是循环移位的核心,它能让索引超出范围时自动回到开头,避免数组越界异常
  • 打印时可以直接用new string(char[])把字符数组转成字符串,简化嵌套循环的打印逻辑

内容的提问来源于stack exchange,提问作者Fidan Agushi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:35:07