c# - 使用 maxchar 居中和拆分字符串

标签 c# .net winforms

我花了很多时间思考如何解决,这是我的功能:

private String TextAlignCenter(String Line)
{
    String CenterLine = String.Empty;

    if (Line.Length > 36)
    {
        for (int i = 0; i < Line.Length; i += 36)
        {
            if ((i + 36) < Line.Length)
                TextAlignCenter(Line.Substring(i, 36));
            else
                TextAlignCenter(Line.Substring(i));
        }
    }
    else
    {
        Int32 CountLineSpaces = (int)(36 - Line.Length) / 2;
        for (int i = 0; i < CountLineSpaces; i++)
        {
            CenterLine += (Char)32;
        }
        CenterLine += Line;
    }
    Console.WriteLine(CenterLine);
    return CenterLine;
}

此函数将字符串拆分为 36 个字符的一部分,然后将结果字符与空格相加以制作居中文本: 例如:

string x = "27 Calle, Col. Ciudad Nueva, San Pedro Sula, Cortes";
TextAlignCenter(x); 

结果:

Line1: 27 Calle, Col. Ciudad Nueva, San Ped
Line2:          ro Sula, Cortes
Line3:[EmptyLine]

第 1 行和第 2 行是正确的,但我不需要第 3 行,我如何才能防止打印这个不必要的行?

更新:

行被添加到 ArrayList()

ArrayList Lines = new ArrayList();
string x = "27 Calle, Col. Ciudad Nueva, San Pedro Sula, Cortes";
Lines.Add(TextAlignCenter(x));
Console.WriteLine(Lines.Count);

最佳答案

您所需要的只是完整 block 循环最后 block 的特殊条件:

    public static IEnumerable<String> SplitByLength(String value, 
      int size, // you may want to set default for size, i.e. "size = 36"
      Char padding = ' ') {

      if (String.IsNullOrEmpty(value)) 
        yield break; // or throw an exception or return new String(padding, size);

      if (size <= 0)
        throw new ArgumentOutOfRangeException("size", "size must be a positive value");

      // full chunks with "size" length
      for (int i = 0; i < value.Length / size; ++i)
        yield return value.Substring(i * size, size);

      // the last chunk (if it exists) should be padded
      if (value.Length % size > 0) {
        String chunk = value.Substring(value.Length / size * size);

        yield return new String(padding, (size - chunk.Length) / 2) + 
          chunk + 
          new String(padding, (size - chunk.Length + 1) / 2);
      }
    }
...

String source = "27 Calle, Col. Ciudad Nueva, San Pedro Sula, Cortes";

// I've set padding to '*' in order to show it
// 27 Calle, 
// Col. Ciuda
// d Nueva, S
// an Pedro S
// ula, Corte
// ****s*****
Console.Write(String.Join(Environment.NewLine,
  SplitByLength(source, 10, '*')));

你的样本:

  string x = "27 Calle, Col. Ciudad Nueva, San Pedro Sula, Cortes";
  List<String> lines = SplitByLength(x, 36).ToList();

关于c# - 使用 maxchar 居中和拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32391881/

相关文章:

c# - 为什么GridViewRow的 "FindControl"找不到下拉列表?

c# - Thread.Sleep 实现

c# - 如何仅从 Windows 窗体 DateTimePicker 控件获取日期值?

c# - 将所有者授予从另一个线程调用的 MessageBox

c# - 在 API 中抛出异常的正确时间是什么时候?

c# - 如何防止颜色混合?

C# 如何在非静态成员函数上调用 Action?

.net - Autofac 和 Func 工厂

.net - 将 "Help"集成到 WinForms 应用程序中

c# - 正则表达式系统的 IndexOutOfRangeException