Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center and Split string with maxchar

Tags:

c#

.net

winforms

I have many hours thinking how i can solve, this is my funtion:

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;
}

This function split a string in parts of 36 characters then add the resultant characters with spaces for make a centered text: For example:

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

Result:

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

Line1 and Line2 are correct but i dont need the Line3, how i can prevent to print this unnecessary line?

UPDATE:

The lines are added into a ArrayList()

ArrayList Lines = new ArrayList();
string x = "27 Calle, Col. Ciudad Nueva, San Pedro Sula, Cortes";
Lines.Add(TextAlignCenter(x));
Console.WriteLine(Lines.Count);
like image 681
Jonathan Nuñez Avatar asked Sep 04 '15 06:09

Jonathan Nuñez


People also ask

How do I split a string into substrings?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

Does string split remove whitespace?

Split method, which is not to trim white-space characters and to include empty substrings.


3 Answers

All you need is a loop for full chunks and a special condition for the last one:

    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, '*')));

Your sample:

  string x = "27 Calle, Col. Ciudad Nueva, San Pedro Sula, Cortes";
  List<String> lines = SplitByLength(x, 36).ToList();
like image 118
Dmitry Bychenko Avatar answered Oct 19 '22 21:10

Dmitry Bychenko


You don't need recursive function here. Also some operations are not optimal.

private static String TextAlignCenter(String Line)
{
    int len = 36; // avoid magic numbers
    StringBuilder b = new StringBuilder(); 
    String CenterLine = String.Empty;

    for (int i = 0; i < Line.Length; i += len)
    {
        if ((i + len) < Line.Length)
            b.AppendLine(Line.Substring(i, len));  // add new line at the end                     
        else
        {
            CenterLine = Line.Substring(i);
            int CountLineSpaces = (len - CenterLine.Length) / 2;    
            // new string(' ', CountLineSpaces) replicates ' '  CountLineSpaces times
            CenterLine = new string(' ', CountLineSpaces) + CenterLine;                     
            b.Append(CenterLine);  // string tail, no new line
        }
    }

    Console.WriteLine(b.ToString());
    return b.ToString();
}

fiddle demo

like image 25
ASh Avatar answered Oct 19 '22 21:10

ASh


I would go with Console.Write instead:

private void 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 = (36 - Line.Length) / 2;
        for (int i = 0; i < CountLineSpaces; i++)
        {
            CenterLine += (Char)32;
        }
        CenterLine += Line + Environment.NewLine;
    }
    Console.Write(CenterLine);
}
like image 27
Thomas Ayoub Avatar answered Oct 19 '22 22:10

Thomas Ayoub