Formatting several strings into one whilst maintaining layout - c#

I have a listbox which i am populating with data; a string of variable length and 3 ints formatted to fixed lengths.
I can't work out how to get the string text to take up only x characters
i.e.
30 characters worth of space, if string is 5 characters long add 25 characters worth of padding. If string is 10 characters long add 20 characters of padding.
My latest attempt looked like:
int padding = 30 - item.ProductName.Length;
string prodName = String.Format("{0, " + padding + "}",item.ProductName);
string quant = String.Format("{0,15}", item.GetQuantity);
string price = String.Format("{0,30:C2}", item.LatestPrice);
string total = String.Format("{0,30:C2}", item.TotalOrder);
string temp = prodName + quant + price + total;
return temp;
But that's still not working: http://i.imgur.com/RfxFCO3.png

This should do the trick.
//int padding = 30 - item.ProductName.Length;
string prodName = String.Format("{0, -30}", item.ProductName);
string quant = String.Format("{0,15}", item.GetQuantity);
string price = String.Format("{0,30:C2}", item.LatestPrice);
string total = String.Format("{0,30:C2}", item.TotalOrder);
string temp = prodName + quant + price + total;
return temp;
And if you want Product Names absolutely limited to 30 characters then you'll need to truncate Product Names > 30 characters.
string prodName = String.Format("{0, -30}", item.ProductName.Length > 30 ? item.ProductName.Substring(0,30): item.ProductName);

Related

How do I insert "padding" between two parts of the string?

Let's say I have a string
string totalAmount = "100";
string price = "Price";
ALPHA = Price + totalAmount
I know that one line of the docket can have 42 characters.
I want to print this on a docket such that the "Price" is on the left hand side of the docket and the "totalAmount" is on the right hand side.
How would I do this?
PadRight should help you in this case.
string totalAmount = "100";
string price = "Price";
string result = price.PadRight(42 - totalAmount.Length) + totalAmount;
You can use the String.PadLeft / String.PadRight methods of the .net Framework if you use a font like Courier that have the same width for each character.
string totalAmount = "100".
ALPHA = "Price" + totalAmount.PadLeft(37, " ");
You can use String.PadRight and String.PadLeft to achive this.
string totalAmount = "100".PadLeft(37).
ALPHA = "Price" + totalAmount

Aligning string inside listbox c#

I'm trying to write strings with spaces into a listbox, and keep them aligned.
Here is the code:
List<String> treeNames = new List<String>();
int counter = 1;
treeNames.Add("Input ");
treeNames.Add("Output ");
treeNames.Add("Sequence Type ");
foreach (String currentData in treeNames)
{
listBox1.Items.Add(currentData + " - " + counter.ToString());
counter+=1;
}
Here's what I hope to achieve:
Input - 1
Output - 2
Sequence Type - 3
Instead, I'm getting:
Input - 1
Output - 2
Sequence Type - 3
Any ideas how can I align them?
foreach (String currentData in treeNames)
{
listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("- " + counter.ToString())));
counter += 1;
}
You can use String.PadRight method which returns a new string that left-aligns the characters in the string by padding them with spaces on the right for a specified total length.
Let's say you have 20 character maximum length for a name:
public String stringHighscore()
{
return name + name.PadRight(20 - name.Length) + "\t\t\t" + score.ToString();
}
If your name's length is 13, this will add 7 space characters. If your name's length is 9, this will add 11 space characters. That way all your name's lengths will equal 20 at the end.

Generating 6 digit number

I am retrieving a number of records from a database, which I append to some string - for example:
spouse counter=1;
counter=1+counter;
then I get customerID in the following way:
customerID = "AGP-00000" + counter;
so that customerID will be AGP-000001.
For counter value 2 - the customerID string will be AGP-000002.
My problem is that, if counter is 10 then customer ID will be AGP-0000010, and I want it to be AGP-000010.
How can I ensure that customer ID is always like AGP-000010?
int number = 1;
string customerID = "AGP-" + number.ToString("D6");
customerID will be: "AGP-000001"
See: How to: Pad a Number with Leading Zeros
Not sure if it's the most efficient way, but it works
string str = "AGP-00000";
int counter = 100;
str = str.Substring(0, str.Length - counter.ToString().Length + 1);
str += counter.ToString();

Displaying bandwidth speed in a user-friendly format

I'm looking for a string conversion method that will receive an input of KB/s and converts it to the easiest readable format possible.
e.g. 1500 b/s = 1.46 Kb/s
e.g. 1500 Kb/s = 1.46 Mb/s
e.g. 1500 Mb/s = 1.46 Gb/s
Thanks
Try this:
var ordinals = new [] {"","K","M","G","T","P","E"};
long bandwidth = GetTheBandwidthInBitsPerSec();
decimal rate = (decimal)bandwidth;
var ordinal = 0;
while(rate > 1024)
{
rate /= 1024;
ordinal++;
}
output.Write(String.Format("Bandwidth: {0} {1}b/s",
Math.Round(rate, 2, MidpointRounding.AwayFromZero),
ordinals[ordinal]));
The ordinals (prefixes) available here are Kilo-, Mega-, Giga-, Tera-, Peta-, Exa-. If you really think your program will be around long enough to see Zettabit and Yottabit network bandwidths, by all means throw the Z and Y prefix initials into the array.
To convert from one formatted string to the other, split on spaces, look at the term that will be the number, and then search the term immediately following for one of the prefixes. Find the index of the ordinal in the array, add 1, and multiply by 1024 that many times to get to bits per second:
var bwString= GetBandwidthAsFormattedString(); //returns "Bandwidth: 1056 Kb/s";
var parts = String.Split(bwString, " ");
var number = decimal.Parse(parts[1]);
var ordinalChar = parts[2].First().ToString();
ordinalChar = ordinalChar = "b" ? "" : ordinalChar;
var ordinal = ordinals.IndexOf(ordinalChar)
... //previous code, substituting the definition of ordinal
I made this code in about 30 secondes, so there is no validation, but I think it does what you want
string vInput = "1500 Kb/s";
string[] tSize = new string[] { "b/s", "Kb/s", "Mb/s", "Gb/s" };
string[] tSplit = vInput.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);
double vSpeed = Double.Parse(tSplit[0]) / 1024.0;
vSpeed = Math.Round(vSpeed, 2);
int i = 0;
for(i = 0; i < tSize.Length;++i)
{
if(tSplit[1].StartsWith(tSize[i]))
{
break;
}
}
string vOutput = vSpeed.ToString() + " " + tSize[i+1];

Why Space was not inserted after specified limit in the given code?

I want to insert a space every 34 characters in a string
public string MySplit()
{
string SplitThis = "aaaaaaaaaaaa"; // assume that string has more than 34 chars
string[] array = new string[SplitThis .Length / 34];
for (int i = 1; i <= array.Length; i++)
{
SplitThis .Insert(i * 34, " ");
}
return SplitThis;
}
when I quickwatch "SplitThis .Insert(i * 34, " ");" I can see the space but the resultant string do not show the space. Why?
You are throwing away the result of the insert
Try
SplitThis = SplitThis.Insert(i*34, " ");
But there might be other logic errors in your code because you are amending the same string as you are working one and have calculated the number of iterations based on the length of the string, which is ignoring the fact that the length of the string is changing.

Categories

Resources