adding quotes around date and time, c# - c#

I am currently using the following line:
w.Write(DateTime.Now.ToString("MM/dd/yyyy,HH:mm:ss"));
and it gives and output like:
05/23/2011,14:24:54
What I need is quotations around the date and time, the output should look like this:
"05/23/2011","14:24:54"
any thoughts on how to "break up" datetime, and get quotes around each piece?

Try String.Format:
w.Write(String.Format("\"{0:MM/dd/yyyy}\",\"{0:HH:mm:ss}\"", DateTime.Now));

DateTime.Now.ToString("\\\"MM/dd/yyyy\\\",\\\"HH:mm:ss\\\"")

This will do the trick, too.
string format = #"{0:\""MM/dd/yyyy\"",\""HH:mm:ss\""}" ;
string s = string.Format(format,DateTime.Now) ;
as will this:
string format = #"{0:'\""'MM/dd/yyyy'\""','\""'HH:mm:ss'\""'}" ;
string s = string.Format(format,DateTime.Now) ;
and this
string format = #"{0:""\""""MM/dd/yyyy""\"""",""\""""HH:mm:ss""\""""}" ;
string s = string.Format(format,DateTime.Now) ;
The introduction of a literal double quote (") or apostrophe (') in a DateTime or Numeric format strings introduces literal text. The embedded literal quote/apostrophe must be balanced — they act as an embedded quoted string literal in the format string. To get a double quote or apostrophe it needs to be preceded with a backslash.
John Sheehan's formatting cheatsheets makes note of this...feature, but insofar as I can tell, the CLR documentation is (and always has been) incorrect WRT this: the docs on custom date/time and numeric format strings just says that "[any other character] is copied to the result string unchanged.".

string part1 = DateTime.Now.ToString("MM/dd/yyyy");
string part2 = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine("\""+part1+"\",\""+part2+"\"");
Works just fine. May not be the best way though

I'm not sure about the type of w but if it supports the standard set of Write overloads the following should work.
w.Write(#"""{0}""", DateTime.Now.ToString(#"MM/dd/yyyy"",""HH:mm:ss")));
If not then you can do the following
var msg = String.Format(#"""{0}""", DateTime.Now.ToString(#"MM/dd/yyyy"",""HH:mm:ss"))));
w.Write(msg);

The following version, though obvious, will not work:
w.Write(DateTime.Now.ToString("\"MM/dd/yyyy\",\"HH:mm:ss\""));
This will output:
MM/dd/yyyy,HH:mm:ss
So don't do that.

Related

C# 6 how to format double using interpolated string?

I have used interpolated strings for messages containing string variables like $"{EmployeeName}, {Department}". Now I want to use an interpolated string for showing a formatted double.
Example
var aNumberAsString = aDoubleValue.ToString("0.####");
How can I write it as an interpolated string? Something like $"{aDoubleValue} ...."
You can specify a format string after an expression with a colon (:):
var aNumberAsString = $"{aDoubleValue:0.####}";
A colon after the variable specifies a format,
Console.Write($"{aDoubleValue:0.####}");
Or like this:
Console.Write($"{aDoubleValue:f4}");

Fixed string Regular Expression C#

Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help
string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;
if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h
String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());

Regular expression for parsing CSV

I'm trying to parse a CSV file in C#. Split on commas (,). I got it to work with this:
[\t,](?=(?:[^\"]|\"[^\"]*\")*$)
Splitting this string:
2012-01-06,"Some text with, comma",,"300,00","143,52"
Gives me:
2012-01-06
"Some text with, comma"
"300,00"
"143,52"
But I can't figure out how to lose the "" from the output so I get this instead:
2012-01-06
Some text with, comma
300,00
143,52
Any suggestions?
If you are trying to parse a CSV and using .NET, don't use regular expressions. Use a component that was created for this purpose. See the question CSV File Imports in .Net.
I know the CSV specification looks simple enough, but trust me, you are in for heartache and destruction if you continue down this path.
Why are you using regular expressions for this? Ensuring the file is well-formed?
You can use String.Replace()
String s = "Some text with, comma";
s = s.Replace("\"", "");
// After matched
String line = 2012-01-06,"Some text with, comma",,"300,00","143,52";
String []fields = line.Split(',');
for (int i = 0; i < fields.Length; i++)
{
// Call a function to remove quotes
fields[i] = removeQuotes(fields[i]);
}
String removeQuotes(String s)
{
return s.Replace("\"", "");
}
So, something like this. Again, I wouldn't use RegEx for this purpose, but YMMV.
var sp = Regex.Split(a, "[\t,](?=(?:[^\"]|\"[^\"]*\")*$)")
.Select(s => Regex.Replace(s.Replace("\"\"","\""),"^\"|\"$","")).ToArray();
So, the idea here is that first of all, you want to replace double double quotes with a single double quote. And then that string is fed to the second regex which simply removes double quotes at the beginning and end of the string.
The reason for the first replace is because of strings like this:
var a = "1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\" Dude\",\"\",\"5000.00\"";
So, this would give you a string like this: ""Extended Edition"", and the double quotes need to be changed to single quotes.

parsing a string into int/long using custom format strings

In C#.Net, here's a simple example of how to format numbers into strings using custom format strings:
(example taken from: http://www.csharp-examples.net/string-format-int/)
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
Is there a way to convert this formatted string back into a long/integer ? Is there someway to do this :
long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
I saw that DateTime has a method ParseExact which can do this work well. But I did not see any such thing for int/long/decimal/double.
You can regex out all of the non numeric numbers, and what you're left with is a string of numbers that you can parse.
var myPhoneNumber = "89-5871-2551";
var strippedPhoneNumber = Regex.Replace(myPhoneNumber, #"[^\d]", "");
int intRepresentation;
if (Int32.TryParse(strippedPhoneNumber, out intRepresentation))
{
// It was assigned, intRepresentation = 8958712551
// now you can use intRepresentation.
} else {
// It was not assigned, intRepresentation is still null.
}
Well, you can always do
long PhoneNumber = Int32.Parse("89-5871-2551".
Replace(new char[]{'-','+',whatever..}).Trim());
By the way, considering that you're parsing a string received from some IO, I would suggest to use more secure (in terms of conversion) Int32.TryParse method.
The way like you described doesn't actually exist.
Just Regex out all of the non-numeric characters, then parse that string.

C# How to Format a Number to a Hexicadecimal with a Prefix '0x'

How to Format a Number to a Hexicadecimal with a Prefix '0x'?
Such as:
int space = 32;
MessageBox.Show(space.ToString("'0x'X4")); // Output 0xX4 instead of 0x0020
I followed this link:
Custom Numeric Format Strings
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
Literal string delimiter: Indicates that the enclosed characters should be copied to the result string unchanged.
But it does not work for 'X4' (it does work for '#'), kind of weird.
I'm using it in a DataGridView.DefaultCellStyle.Format, so I cannot use:
"0x{0:X4}", space
Thanks.
Peter
int space = 32;
MessageBox.Show("0x"+space.ToString("X"));
If you want to output 0x0020:
MessageBox.Show("0x"+space.ToString("X4"));
string.Format("0x{0:x8}", ii);

Categories