/t not working in C# console - c#

when i put \t in the console.writelin() it doesn't work
if (reader.HasRows)
{
Console.WriteLine("|{0}|\t|{1}|\t|{2}|\t|{3}|\t|{4}|", reader.GetName(0),
reader.GetName(1), reader.GetName(2), reader.GetName(3), reader.GetName(4));
while (reader.Read())
{
Console.WriteLine("|{0}|\t|{1}|\t|{2} EGP|\t|{3} EGP|\t|{4}|", reader.GetString(0),
reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetString(4));
}
}
the result is ::
|Product Name| |Quantity| |price per item | |Total| |Code|
|a| |1| |0 EGP| |1 EGP| |12|
even when i use {0,10} or {0,-10} it is not working
thank you.

Yes, it's work.
You sould imagine tabs as columns markers. So when you put a \t you are saying to Console: jump to the next available column mark. In your header 'Product Name' has revased the first tab column, so when Console process \t, it jumps to 2nd column. Instead, in the data, 'a' is small enought and can jump to the 1st column.
This will output with correct format:
Console.WriteLine(string.Format("|{0,-15}|", "Product Name"));
Console.WriteLine(string.Format("|{0,-15}|", "a"));
You can see it working at http://rextester.com/TUVX20333

Q
What does the \t do?
A
It moves the cursor to the next column that is a multiple of 8.
This is exactly what is happening in your example. Maybe not what you wanted but definitely what you asked for. ;)

\t really works here. But you are expecting something else. If you can mention what kind of output you are expecting. It would be easy to help.
Edit: The below code would create the header of the table as you have expected. Adjust the second number inside the {} to suit your column width.
Console.WriteLine(string.Format("|{0,-20}|{1,-20}|{2,-20}|{3,-20}|{4,-20}|", "Product Name", "Quantity", "Price per item", "Total", "Code"));

A stopgap measure, if you know the length of your columns, is to use string.PadRight. BUT it is messy:
Console.WriteLine("{0}{1}{2}{3}{4}",
("|" + reader.GetString(0) + "|").PadRight(20, ' '),
("|" + reader.GetInt32(1) + "|").PadRight(20, ' ')
("|" + reader.GetInt32(2) + "EGP|").PadRight(20, ' ')
("|" + reader.GetInt32(3) + "EGP|").PadRight(20, ' ')
("|" + reader.GetString(4) + "|").PadRight(20, ' '));
Although putting that into a separate method is straight forward.
If you really want to use \t then you can write a separate method to calculate how many tabs to add. Once again you will need to know the length of each field:
string ToTabColumn(string text, int length)
{
int tabSize = 8; // no easy way of getting environment tab length
int colSize = text.Length + Convert.ToInt32(Math.Ceil((double)(length - text.Length) / tabSize));
return text.PadRight(colSize, '\t');
}

Related

Isolating values from a listbox line

I have got a line in a lisbox that i need so i can print out my receipt for the end of my 12 grade project im doing.
Example of my line :"cha1 Adidas Stan Smith White 1 2" (its padded).
Now what i want to do is isolate like cha1, Adidas stan Smith White,1,2 to add to my Microsoft Access Database, i somehow managed to do it with substring but i screwed up my code and now i cant do it , can somebody help me please ?
My code ,that used to work , looks like this :
foreach (string item in lstpreview.Items)
{
//create the string to print on the reciept
string nomeproduto = item;
float quantidade = float.Parse(item.Substring(item.Length -5, 5));
float precounitario = float.Parse(item.Substring(item.Length - 5, 5));
string totalproduto = item.Substring(item.Length - 6, 6);
txt1.Text = Convert.ToString(quantidade);
txt2.Text = Convert.ToString(precounitario);
//MessageBox.Show(item.Substring(item.Length - 5, 5) + "PROD TOTAL: " + totalproduto);
//float totalprice = 0.00f;
}
You say that the line is padded, but do not give any details. If you know that the first field is always the first 4 characters of the line, you can isolate it with string.Substring:
string field1 = line.Substring(0, 4);
and similarly for the other fields.
P.S. Please edit your post and remove the swear word.
Edit after parsing code added
I don't understand your comment, what is "your negative value"? Run the code in the debugger and find which line causes the error. Please post the exact error message.
Is there a reason for converting the substring to a float and then back to a string? I can imagine that you might want to validate that the field is numeric, but then you would be better to use TryParse.
Your second comment is helpful. The last 5 characters of the line are not all numeric, that's the problem.
Done it with this snippet of code together with a for each loop.
string[] caracteresnastring = item.Split(new char[] { ',' }.ToArray());
string code = caracteresnastring[0];
string name = caracteresnastring[1];
string price = caracteresnastring[2];
string quantity = caracteresnastring[3];

Check empty Char in a array C#

I'm reading a field On a table it only has 3 values ("",ESD,R&S)
I don't know exactly why, but when I read the R&S value, the print out label is R ("empty space") S
this is the code I'm using:
char[] area = read1[8].ToString().ToCharArray();
// if array is less than one do nothing
if (area.Length > 1)
{
//trying to use this to check if the second item of array is the "&" symbol (print this format data)
if (area[1].ToString() == "&")
{
Arealbl.Text = area[0].ToString() + "\n" + "&" + "\n" + area[2].ToString();
}
//else print out this format data
else
{
Arealbl.Text = area[0].ToString() + "\n" + area[1].ToString() + "\n" + area[2].ToString();
}
}
I using this code because I haven't found an easy way to put a label on vertical.
The & is a special char in MenuItems, Labels and Buttons, used to indicate that the next char should be underscored. When you manage to focus Arealbl and hit Alt you might see that.
Set
Arealbl.UseMnemonic = false;
somewhere. Like with the designer.
In addition to #Henk Holterman's answer, here are a few code review suggestions. You can access a string as an array, so there is no need to .ToString().ToCharArray(), just to .ToString() everything further down the method. Simplifying the concatenation to a string.Format can help improve readability and assuming you don't have to do this a large number of times (tens of thousands) it shouldn't impact performance.
string area = read1[8].ToString()
if(area.Length < 3) { return; } //exit early on error conditions.
// if array is less than one do nothing
Arealbl.UseMnemonic = false; //only add this if you cannot guarantee it will be set.
Arealbl.Text = string.Format("{0}\n{1}\n{2}", area[0], area[1], area[2]);

c# Using Substring and Regular Expressions to edit a large string

The string, when displayed looks like: value1, value2, value3, value4, value5 etc..
What I want the string to do once I display it is (removing spaces and commas, i assume I can use index + 2 or something to get past the comma):
value1
value2
etc...
lastKnownIndexPos = 0;
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(unformatedList, ",?")) //Currently is ',' can I use ', '?
{
list += unformatedList.Substring(lastKnownIndexPos, m.Index - 1) + "\n\n"; //-1 to grab just the first value.
lastIndex = m.Index + 2; //to skip the comma and the space to get to the first letter of the next word.
//lastIndex++; //used this to count how many times it was found, maxed at 17 (have over 100):(
}
//MessageBox.Show(Convert.ToString(lastIndex)); //used to display total times each was found.
MessageBox.Show(list);
At the moment the message box does not show any text, but using the lastIndex I get a value of 17 so I know it works for part of it :P
That's easy (I'm using System.Linq here):
var formatted = string.Join("\n\n", unformatedList.Split(',').Select(x => x.Trim()));
MessageBox.Show(formatted);
An alternative approach, as swannee pointed out, would be the following:
var formatted = Regex.Replace(unformatedList, #"\s*,\s*", "\n\n").Trim();
Edit:
To make the above examples work regardless of how you use the result string, you should use Environment.NewLine instead of "\n".
One way is to simply replace the ", " with a newline.
MessageBox.Show( unformatedList.Replace(", ", "\n") );
Or heck, why not just use string.Replace?
var formatted = unformattedList.Replace(", ", "\n\n");

C# : Printing variables and text in a textbox

I need to know the command that I can print a sentence like "the item Peter at row 233 and column 1222 is not a number " .
I far as now I have made this:
string[] lineItems = (string[])List[]
if (!Regex.IsMatch(lineItems[0], (#"^\d*$")))
textBox2.Text += " The number ,lineItems[0], is bigger than
10 " + Environment.NewLine;
I want to print the array fields that have error. So if it finds something it will print it.
I made a code that correctly prints that there is an error on this line of the array, but I cant print the item of the array.
I need to have an Environment.NewLine because I will print many lines.
Thanks ,
George.
foreach (int lineNumber in lineItems)
{
if (lineNumber > 10)
textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";
}
Something like this should work, (I have not checked the c# code, I am working on a mac at the moment)
TextBox2.Text="This is FirstLine\nThis is Second Line";
The code is not compilable absolutely, but I may be understand what you're asking about.
If you are asking about how to compose the string of text box, by adding new strings to it, based on some desicional condition (regex), you can do folowing, pseudocode:
StringBuilder sb = new StringBuidler();
if (!Regex.IsMatch(lineItems[i], (#"^\d*$")))
sb.Append(string.Format(The number ,{0}, is bigger than 10, lineItems[i]) + Environment.NewLine);
textBox2.Text = sb.ToString();
If this is not what you want, just leave the comment, cause it's not very clear from post.
Regards.

How to check if a position in a string is empty in c#

I have strings with space seperated values and I would like to pick up from a certain index to another and save it in a variable. The strings are as follows:
John Doe Villa Grazia 323334I
I managed to store the id card (3rd column) by using:
if (line.length > 39)
{
idCard = line.Substring(39, 46);
}
However, if I store the name and address (1st and 2nd columns) with Substring there will be empty spaces since they are not of the same length (unlike the id cards). How can I store these 2 values and removing the unneccasry spaces BUT allowing the spaces between name and surname?
Try this:
string line = " John Doe Villa Grazia 323334I";
string name = line.Substring(02, 16).Trim();
string address = line.Substring(18, 23).Trim();
string id = line.Substring(41, 07).Trim();
var values = line.Split(' ');
string name = values[0] + " " + values[1];
string idCard = values[4];
It will be impossible to do without database lookups on names if there aren't spaces for sure in the previous columns.
Are these actually space separated or are they really fix width columns?
By that I mean do the "columns" start at the same index into the string in each case - from the way you're describing the data is sounds like the later i.e. the ID column is always column 39 for 7 characters.
In which case you need to a) pull the columns using the appropriate substring calls as you're already doing and then, use "string ".Trim() to cut off the spaces.
If the rows, are, as it seems fixed with then you don't want to use Split at all.
How can you even get the ID like that, when everything in front of it is of variable length? If that was used for my name, "David Hedlund 323334I", the ID would start at pos 14, not 39.
Try this more dynamic approach:
var name = str.Substring(0, str.LastIndexOf(" "));
var id = str.Substring(str.LastIndexOf(" ")+1);
Looks like your parsing strategy will cause you a lot of trouble. You shouldn't count on the string's size in order to parse it.
Why not save the data in CSV format (John Doe, Villa Grazia, 323334I)?
that way, you can assume that each "column" will be separated by a comma which will make your parsing efforts easier.
Possible "DOH!" question but are you sure they are spaces and not Tabs? Looks like it "could" be a tab seperated file?
Also for browie points you should use String.Empty instead of ' ' for comparisons, its more localisation and memory friendly apparently.
The first approach would be - as already mentioned - a CSV-like structure with a defined token as the field separator.
The second one would be fixed field lengths so you know the first column goes from char 1 to char 20, the second column from char 21 to char 30, and so on.
There is nothing bad about this concept besides that the human readability may be poor if the columns are filled up to their maximum so no spaces remain between them.
You could write a helper function or class which knows about the field lengths and provides an index-based, fault-tolerant access to the particular column. This function would extract the particular string parts and remove the leading and trailing spaces but leave the spaces in between as they are.
If your values have fixed width, best not split it but use the right indexes in your array.
const string input = "John Doe Villa Grazia 323334I";
var name = input.Substring(0, 15).TrimEnd();
var place = input.Substring(16, 38).TrimEnd();
var cardId = input.Substring(39).TrimEnd();
Assuming your values cannot contain two sequential spaces in them we can maybe use " " (double space" as a separator?
The following code will split your string based on the double space
const string input = "John Doe Villa Grazia 323334I";
var entries = input.Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries)
.Select(s=>s.Trim()).ToArray();
string name = entries[0];
string place = entries[1];
string idCard = entries[2];

Categories