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

如何在C#控制台中为整段文本添加左右内边距

问题分析
  • 核心问题1:PadLeft/PadRight方法的输入参数是填充后的字符串总长度,你当前代码传入原长度+边距值虽然能实现给整个字符串首尾加对应数量的空格,但仅对单行文本生效
  • 核心问题2:文本自动换行后,除第一行外的其余行没有左边距,也没有统一的右边距对齐,所以和期望效果不符
  • 额外小问题:拼接后的字符串末尾会多一个多余空格,需要先去除再做边距处理
调整后代码

支持自动换行的完整版本(适配多行文本的统一边距需求)

using System.Text;

public static string Format(List<string> list, int leftMargin, int rightMargin, int lineMaxWidth = 80)
{
    // 1. 先把列表拼接成规范的无多余空格的文本
    string content = "";
    char[] punctuation = ".,?!".ToCharArray();
    foreach (string item in list)
    {
        if (item.IndexOfAny(punctuation) == 0 && !string.IsNullOrEmpty(content))
        {
            // 去掉标点前的多余空格
            content = content.Remove(content.Length - 1);
        }
        content += $"{item} ";
    }
    // 去掉末尾多余的空格
    content = content.TrimEnd();
    
    // 2. 计算单行有效内容宽度 = 总行宽 - 左边距 - 右边距
    int validLineWidth = lineMaxWidth - leftMargin - rightMargin;
    if (validLineWidth <= 0) validLineWidth = 1;
    
    // 3. 把长文本拆成多行,尽量不在单词中间断行
    List<string> lines = new List<string>();
    int currentIndex = 0;
    while (currentIndex < content.Length)
    {
        int takeLength = Math.Min(validLineWidth, content.Length - currentIndex);
        if (takeLength < content.Length - currentIndex)
        {
            int lastSpaceIndex = content.LastIndexOf(' ', currentIndex + takeLength, takeLength);
            if (lastSpaceIndex > currentIndex)
            {
                takeLength = lastSpaceIndex - currentIndex;
            }
        }
        lines.Add(content.Substring(currentIndex, takeLength).TrimEnd());
        currentIndex += takeLength;
        if (currentIndex < content.Length && content[currentIndex] == ' ')
        {
            currentIndex++;
        }
    }
    
    // 4. 给每一行单独加左右边距
    StringBuilder result = new StringBuilder();
    string leftPadding = new string(' ', leftMargin);
    string rightPadding = new string(' ', rightMargin);
    foreach (string line in lines)
    {
        string paddedLine = leftPadding + line.PadRight(validLineWidth) + rightPadding;
        result.AppendLine(paddedLine);
    }
    
    return result.ToString().TrimEnd();
}

调用时可根据实际展示区域的宽度调整lineMaxWidth参数,默认值80是常规文本编辑器的默认行宽。

不需要自动换行的简化版本

如果只需要给整段文本首尾加边距,不需要处理换行场景,直接用下方代码即可:

public static string Format(List<string> list, int leftMargin, int rightMargin)
{
    string content = "";
    char[] punctuation = ".,?!".ToCharArray();
    foreach (string item in list)
    {
        if (item.IndexOfAny(punctuation) == 0 && !string.IsNullOrEmpty(content))
        {
            content = content.Remove(content.Length - 1);
        }
        content += $"{item} ";
    }
    content = content.TrimEnd();
    return new string(' ', leftMargin) + content + new string(' ', rightMargin);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:18:02