This is a mirror of official site: http://jasper-net.blogspot.com/

C#/.NET Little Wonders: An Oft Overlooked String Constructor

| Sunday, September 4, 2011
Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders post can be found here.

I’m going to begin a series of Little Wonders in the BCL String class.  Yes, we all work with strings in .NET daily, so perhaps you already know most of these.  However, there are a lot of little fun things that the String class can do that often get overlooked and these next few posts will be dedicated to those String Little Wonders.

Today, in particular, we will discuss an often overlooked constructor that can be useful for constructing strings of a repeated character.

Background

Sometimes in code you’ll see someone coding an application that writes to console or a log file, and for separation you may want a line of dashes to divide sections.  Perhaps, you want a piece of text centered in a dashed line such as:

    ====================Acount 11123452===================

To create such a thing, we could easily make a heading using calculations such as this:

public static string MakeHeading(string text)
{

// yes we would validate all input first, but for brevity assume all valid
// left space is area / 2, right is same unless text is odd length, then same + 1
int leftLength = (80 - text.Length) / 2;
int rightLength = text.Length % 2 == 0 ? leftLength : leftLength + 1;

// make line!  Now all we need to do is code CreateLine()
return CreateLine(leftLength) + text + CreateLine(rightLength);

}

But how do we make that line?  Well, we know we want to repeat the character for leftLength times, but what’s the best way to do this.

Possible Methods:

Well, there are several ways we can accomplish making a string of repeated characters.  Obviously the first is to just build in a for loop, and because we know that concatenating strings repeatedly is very slow, we’ll optimize a bit and use a StringBuilder.  Further, because we know StringBuilder will resize when it grows beyond it’s buffer, we’ll pre-size the buffer using the StringBuilder constructor that takes a starting buffer size it to avoid this cost:

public static string CreateLine(int size)
{

// pre-size string buffer to max to avoid resizing
var builder = new StringBuilder(size);

for (int j = 0; j < size; j++)
{

builder.Append('-');
}
return builder.ToString();
}

Read more: James Michael Hare
QR: c.net-little-wonders-an-oft-overlooked-string-constructor.aspx

Posted via email from Jasper-net

0 comments: