Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "Space(n)" method in C#/.Net?

Tags:

c#

.net

I'm converting an ancient VB6 program to C# (.Net 4.0) and in one routine it does lots of string manipulation and generation. Most of the native VB6 code it uses have analogues in the C# string class, e.g., Trim(). But I can't seem to find a replacement for Space(n), where it apparently generates a string n spaces.

Looking through the MSDN documentation, there seems to be a Space() method for VB.Net but I couldn't find it mentioned outside of a VB.Net context. Why is this? I thought all the .Net languages share the same CLR.

Does C# or .Net have a generic Space() method I can use in C# that I'm just overlooking somewhere?

N.B. I'm aware that writing one-liners to generate n-spaces is a popular quiz-question and programmers' bar-game for some programming languages, but I'm not looking for advice on that. If there's no native way to do this in C#/.Net it's easy enough to write a simple method; I just don't want to reinvent the wheel.

like image 514
user316117 Avatar asked Mar 24 '14 18:03

user316117


People also ask

What is N in C#?

"\n" is just a line feed (Unicode U+000A). This is typically the Unix line separator. "\r\n" is a carriage return (Unicode U+000D) followed by a line feed (Unicode U+000A). This is typically the Windows line separator.


1 Answers

Use this constructor on System.String:

new String(' ', 10);

http://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx

Here's a neat extension method you can use, as well (although it's probably better just to use the String constructor and save the extra method call):

public static class CharExtensions {     public static string Repeat(this char c, int count)     {         return new String(c, count);     } } ... string spaces = ' '.Repeat(10); 
like image 128
NathanAldenSr Avatar answered Oct 17 '22 11:10

NathanAldenSr