加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用maxchar的Center和Split字符串

发布时间:2020-12-15 08:47:32 所属栏目:百科 来源:网络整理
导读:我有很多小时在思考如何解决,这是我的功能: 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.Substri
我有很多小时在思考如何解决,这是我的功能:
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,San Ped
Line2:          ro Sula,Cortes
Line3:[EmptyLine]

Line1和Line2是正确的,但我不需要Line3,我怎么能防止打印这条不必要的线?

更新:

这些行被添加到ArrayList()中

ArrayList Lines = new ArrayList();
string x = "27 Calle,Cortes";
Lines.Add(TextAlignCenter(x));
Console.WriteLine(Lines.Count);

解决方法

您只需要一个完整块的循环和最后一个的特殊条件:
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,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,Cortes";
  List<String> lines = SplitByLength(x,36).ToList();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读