The .NET blog

Creating and filling strings of a certain length

September 9, 2008

Sometimes, you need a string of a certain length, filled with a certain character, usually whitespace. I use it quite a bit, to replace a certain piece of text with an equal amount of whitespaces. But if all you have is the fill character and a desired length, how do you get a proper string? In a lot of languages, you would have to use e.g. a for-loop to loop X number of times and append to a resulting string, but not with the .NET framework. The String class comes with a constructor which allows you to accomplish the above very easily. Here is an example:

string whitespace = new String(' ', 10);

Or perhaps you need something that will look like a password?

string password = new String('*', 8);

Just another one of those small things that makes the .NET framework such a pleasure to work with.

Filed under: C# — admin @ 10:56 am

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment




© net-tutorials.com 2006 - 2010