Hello,
I am trying to format a string in C# but am having trouble trying to set the width. Is there a way to use a variable int as the width instead of having to declare a static width?

here is my code now...

for (int i = 0; i < max; i++)
{
    string newString = String.Format("{0,15:D}{1,15:D}", i+1, squares[i]);
    System.Console.WriteLine(newString);
}

what I would like to do is something like this (where width is set elsewhere)

int width = 15;
for (int i = 0; i < max; i++)
{
    string newString = String.Format("{0,width:D}{1,width:D}", i+1, squares[i]);
    System.Console.WriteLine(newString);
}

Is this possible?

Just make a string.Left extension and set the width on your overloaded object[] args....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace daniweb
{
  public partial class frmSerialIP : Form
  {
    public frmSerialIP()
    {
      InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
      for (int i1 = 1; i1 <= 35; i1++)
      {
        string myString = Guid.NewGuid().ToString().Replace("-", string.Empty);
        Console.WriteLine("text text '{0}' more text text", myString.Left(i1));
      }
    }
  }

  public static class Extensions
  {
    /// <summary>
    /// Takes the left N characters of a string
    /// </summary>
    /// <param name="str"></param>
    /// <param name="Length">The number of characters to return</param>
    /// <returns></returns>
    public static string Left(this string str, int Length)
    {
      if (string.IsNullOrEmpty(str) || Length.Equals(0))
        return string.Empty;
      else
        return str.Substring(0, Math.Min(Length, str.Length) - 1);
    }
  }
}
commented: Fan of your code! do snippets +8

Hmmm, that seems overly complex for what should be a simple operation. Are there any other options?

You're kidding. Adding one method named .Left() to simplify a .SubString(0, N); is too complex?

Let me try pasting the code again with irrelevant code removed.

string someString = "abc123".Left(2);

To guarantee a fixed width:

const int TotalWidth = 25;
      string someString = "abc123".Left(2).PadLeft(TotalWidth, '0');
public static string Left(this string str, int Length)
    {
      if (string.IsNullOrEmpty(str) || Length.Equals(0))
        return string.Empty;
      else
        return str.Substring(0, Math.Min(Length, str.Length) - 1);
    }

Is this ok?

int width = 15;
        for (int i = 0; i < 5; i++)
        {
            string newString = String.Format("{0," + width + ":D}{1," + width + ":D}", i + 1, squares[i]);
            System.Console.WriteLine(newString);
        }

Ahh, thats it Ramesh, thats exactly what I was looking for..

"{0," + width + "....

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.