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

C#读取txt单词填入二维char数组左侧底部其余填充+的实现

问题解决代码与说明

核心修正点

  • 原代码在初始化填充+时直接输出数组,未提前写入单词内容
  • 缺少文本拆分、单词填充到左侧和底部的逻辑

完整可运行代码

需提前引入依赖命名空间:

using System.IO;
using System.Linq;

业务代码:

// 读取文件内容并拆分出前5个单词,自动过滤空行和多余空格
string txtFromFile = File.ReadAllText(@"C:\Users\source\names.txt");
string[] words = txtFromFile.Split(new[] { '\r', '\n', ' ' }, StringSplitOptions.RemoveEmptyEntries).Take(5).ToArray();
Console.WriteLine("Words from file:\n{0}", txtFromFile);

int rows = 10;
int columns = 10;
char[,] charArray = new char[rows, columns];

// 第一步:全数组默认填充+
for (int a = 0; a < rows; a++)
{
    for (int b = 0; b < columns; b++)
    {
        charArray[a, b] = '+';
    }
}

// 第二步:填充左侧位置:前5行每行从左到右横向写入对应单词
for (int i = 0; i < words.Length; i++)
{
    // 避免单词长度超过列数溢出
    int maxLen = Math.Min(words[i].Length, columns);
    for (int j = 0; j < maxLen; j++)
    {
        charArray[i, j] = words[i][j];
    }
}

// 第三步:填充底部位置:最后一行从左到右写入所有单词首字母,可自行调整为完整单词
int bottomRow = rows - 1;
int colIndex = 0;
foreach (var word in words)
{
    if (colIndex >= columns) break;
    charArray[bottomRow, colIndex] = word[0];
    colIndex++;
}

// 第四步:统一输出填充完成的数组
for (int a = 0; a < rows; a++)
{
    for (int b = 0; b < columns; b++)
    {
        Console.Write("{0} ", charArray[a, b]);
    }
    Console.Write(Environment.NewLine + Environment.NewLine);
}

自定义填充规则调整

如果需要左侧纵向放置单词,可替换第二步的填充代码:

// 左侧第一列纵向写入所有单词的字符
int rowIdx = 0;
foreach(var word in words)
{
    foreach(var c in word)
    {
        if (rowIdx >= rows) break;
        charArray[rowIdx, 0] = c;
        rowIdx++;
    }
}

如果需要底部完整放置最后一个单词,可替换第三步的填充代码:

// 最后一行横向写入最后一个单词
string lastWord = words.Last();
int maxLen = Math.Min(lastWord.Length, columns);
for(int i=0;i<maxLen;i++)
{
    charArray[rows-1, i] = lastWord[i];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:15:04