Question

i have an array of integer called digits

public String toDecimalString() {
        StringBuilder b = new StringBuilder(9 * digits.length);
        Formatter f = new Formatter(b);
        f.format("%d", digits[0]);
        for(int i = 1 ; i < digits.length; i++) {
            f.format("%09d", digits[i]);
        }
        return b.toString();
    }

I tried

String.Format("%09d", digits[i]);

but I think I'm doing something wrong

Was it helpful?

Solution 4

    public string toDecimalString()
{
    StringBuilder b = new StringBuilder(9 * digits.Length);
    var str = digits[0].ToString("D");
    b.Append(str);
    for (int i = 1; i < digits.Length; i++)
    {
        var str2 = digits[i].ToString("D9");
        b.Append(str2);
    }                
    return b.ToString();
}

Thanks for all the answers, I finally reached a solution as above

OTHER TIPS

I'm not really familiar with java formatters, but I think this is what you want

var str = string.Format("{0:D9}", digits[i]);

Or even better

var str = digits[i].ToString("D9");

To join all these strings I suggest this:

var str = string.Join(string.Empty, digits.Select(d => d.ToString("D9")));

Further Reading

I think you want something like

StringBuilder sb = new StringBuilder();
sb.append(String.Format("DL", digits[i]));
for (int i = 1; i < digits.Length; i++) {    
    sb.append(String.Format("D9", digits[i]));
}

Copy from java code and paste it directly into c# code, then change (which are in your toDecimalString() method):

  • f.format to f.Format
  • digits.length to digits.Length
  • b.toString() to b.ToString()

and then paste this class to your code:

public partial class Formatter: IFormatProvider, ICustomFormatter {
    public String Format(String format, object arg, IFormatProvider formatProvider=null) {
        if(!format.StartsWith("%")||!format.EndsWith("d"))
            throw new NotImplementedException();

        m_Builder.Append(String.Format("{0:D"+format.Substring(1, format.Length-2)+"}", arg));
        return m_Builder.ToString();
    }

    object IFormatProvider.GetFormat(Type formatType) {
        return typeof(ICustomFormatter)!=formatType?null:this;
    }

    public Formatter(StringBuilder b) {
        this.m_Builder=b;
    }

    StringBuilder m_Builder;
}

Note that the class only implemented the minimum requirement as your question stated, you would need to add the code if your further extend the requirement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top