-1

I recently began to learn Ruby and I saw following way to format a string:

"%d"        % 123         #=> "123"
"%08b %02x" % [15, 15]    #=> "00001111 0f"

Is there a way to realize this in C#? I tried a lot, but all attempts failed. Here is a example of one of my attempts:

public static string operator % (string format, IFormatable[] items) {
    for (int n = 0; n < items.Length; n++) format.Replace("%" + n, items[n].ToString());
    return format;
}

"%0 %1" % new string[] { "Foo", "Bar" } // Expected result => "Foo Bar"

I know the Methods like ToString() and PadLeft(), but I wanted to find out, if the so-called Method Extensions also work for operators.

Cubi73
  • 1,891
  • 3
  • 31
  • 52
  • How are you adding this stuff to `string`? – cHao Dec 23 '13 at 02:17
  • 4
    Why do you want to do this exactly? You can already do `string.Format("{0} {1}", new [] {"Foo", "Bar"});`. Most of the "special" operators you want to implement are probably already implemented in an other easier way. If you want to add other functionality to a class look for extension methods. – Pierre-Luc Pineault Dec 23 '13 at 02:18
  • I don't "add" the stuff to string. I use Extension Methods (http://msdn.microsoft.com/en-us/library/bb383977.aspx); I haven't a concrete reason for trying this. I simply wanted to test, if this works :) – Cubi73 Dec 23 '13 at 02:36
  • Why not using python then? – zerkms Dec 23 '13 at 02:44
  • 1
    I don't c# but this what you want http://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx – bjhaid Dec 23 '13 at 02:53

1 Answers1

1

Between the method Convert.ToString() which:

Converts the value of a 16-bit signed integer to its equivalent string representation in a specified base.

and the ToString() formats provided, you have all of the functionality you are looking for. You can also use String.PadLeft to add 0's to the left.

int num = 15;
string binNum = Convert.ToString(num, 2).PadLeft(8,'0'); // value 00001111
string hexNum = Convert.ToString(num, 16).PadLeft(2, '0'); // value 0f
Harrison
  • 3,843
  • 7
  • 22
  • 49
  • Thank you for your answer, but I know these functions. I read something about putting a "this" before the first parameter of a method to make it a Extension Method. So I wanted to try, if this also works with operators. And that's the topic of my question. Sorry if this was not clear. – Cubi73 Dec 24 '13 at 01:11