Is it possible to use String.Format () to enter a specific string with arbitrary characters?
Console.WriteLine("->{0,18}<-", "hello"); Console.WriteLine("->{0,-18}<-", "hello"); returns -> hello<- ->hello <-
Now I want the spaces to be an arbitrary character. The reason I cannot do this with padLeft or padRight is because I want to be able to create a format string in another place / time, then formatting is actually done.
- EDIT -
It can be seen that there seems to be no existing solution to my problem, I came up with this (after Think Before Coding suggestion )
- EDIT2 -
I needed more complex scripts, so I went for the second sentence of Think Before Coding
[TestMethod] public void PaddedStringShouldPadLeft() { string result = string.Format(new PaddedStringFormatInfo(), "->{0:20:x} {1}<-", "Hello", "World"); string expected = "->xxxxxxxxxxxxxxxHello World<-"; Assert.AreEqual(result, expected); } [TestMethod] public void PaddedStringShouldPadRight() { string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-20:x}<-", "Hello", "World"); string expected = "->Hello Worldxxxxxxxxxxxxxxx<-"; Assert.AreEqual(result, expected); } [TestMethod] public void ShouldPadLeftThenRight() { string result = string.Format(new PaddedStringFormatInfo(), "->{0:10:L} {1:-10:R}<-", "Hello", "World"); string expected = "->LLLLLHello WorldRRRRR<-"; Assert.AreEqual(result, expected); } [TestMethod] public void ShouldFormatRegular() { string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-10}<-", "Hello", "World"); string expected = string.Format("->{0} {1,-10}<-", "Hello", "World"); Assert.AreEqual(expected, result); }
Since the code was too large to post, I moved it to github as an entity:
http://gist.github.com/533905#file_padded_string_format_info
There, people can easily branch it and that's it :)
c # formatting padding string.format
Boris Callens Feb 12 '09 at 12:49 2009-02-12 12:49
source share