This question already has answers here:
C# DateTime to "YYYYMMDDHHMMSS" format
(18 answers)
Closed 5 years ago.
I developing a xamarin form app and I am assigning the current date time as a Filename for image. Currently the image is saved as "7202017 53150 PM.jpg". I want it to be saved like this "720201753150PM.jpg". How can I remove the space between the date and time?
I tried like below but it did not work.
string _imagename = DateTime.Now.ToString();
_imagename.Replace(" ", string.Empty);
Actually the String.Replace() Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string(in short it won't change the actual string) So you need to assign the result to another variable. And perform the replace operation there.
But Why you go for another replace? whynot use .ToString() like the following?
string format = "Mddyyyyhhmmsstt";
string _imagename = String.Format("{0}.jpg",DateTime.Now.ToString(format))
You need to assign the new value as string is immutable:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
This is fastest way I know:
Regex.Replace(_imagename, #"\s+", "")
Looking at your string ill also suggest replace spaces with a empty string. And you could do it by applying built in Replace method:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
If you want to order by file name I'd suggest to use a notation like yyyyMMddHHmmss. That way, with increasing date/time the sort order will also increase.
Other than that, strings are immutable in c#. Thus calling Replace does not change the original string. You need to assign the result to your variable as #Romano Zumbé pointed out.
You can just use a format string like the following (including the sorting suggestion):
string imagename = $"{DateTime.Now:yyyyMMddHHmmss}.jpg";
otherwise it would be:
string imagename = $"{DateTime.Now:Mddyyyyhmmsstt}.jpg";
Related
This question already has answers here:
Most efficient way to concatenate strings?
(18 answers)
Closed 3 years ago.
I have string that i need to combine with another string , for example
string string1 = "cars"; // the text is just for example
string string2 = "white";
// then
string string1 = string1 + string2;
// or
string string1 += string2;
Alright , at first glance it doesn't have any problem right ?
NOPE , it does have problem
when the string.length / the string contain A LOT OF CHARACTER , for example when it contain 100.000 word , it start to get laggy or freeze when i put it inside loop, because it need to copy 100.000 word plus word from the other string everytime it combines string1 with string2 .
Is the any alternative way to add new text to string that contain massive amount of word ?
The correct way to accumulate strings in c# is using StringBuilder.
Example:
StringBuilder sb = new StringBuilder();
sb.Append("...");
sb.Append("...");
....
var result = sb.ToString()
Your solution appear to lag, since every time you "modify" a string a brand new one is created instead, so the garbage collector get a little crazy...
I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.
I have a string like
string variable1="EXAMPLE";
and later somewhere in my code, I use like
Console.WriteLine(variable1.ToLower());
I may use variable1.ToLower() multiple times. But now I want to store the variablename that is converted to Lower in a separate new variable, that is, I have to extract variable1 from Console.WriteLine(variable1.ToLower()); line and store it in a string variable. Is that possible?
My main goal is that, If my code has variable1.ToLower() in too many places, then I have to run an application, that replaces all variable1.ToLower() to a new string that has the value of variable1.ToLower(). Please Note that using too many variable1.ToLower() in a code is a violation.So I am just creating a new variable to store the value of variable1.ToLower() and use that new variable instead of variable1.ToLower() in every place.
Assuming I understand the question, why not just do this?
var lower = variable1.ToLower();
Console.WriteLine(lower);
String.ToLower creates a copy of the original string. So the original string is not modified and you can safely use it otherwise.
string variable1 = "EXAMPLE";
string lowerCaseVariable1 = variable1.ToLower();
Console.WriteLine($"Is still the original string: {variable1}");
Console.WriteLine($"Is the lower case copy of the original string: {lowerCaseVariable1}");
EDIT:
If you want to get the name of the string variable instead of the content, you can use nameof (Link).
string variable1 = "EXAMPLE";
string nameOfVariable1 = nameof(variable1);
Console.WriteLine(variable1.ToLower());
I have two strings:
string strone="what is your name?"
string strtwo="what is your name? what is your school name?"
Any of the strings could be greater here. What I need is to extract string from strtwo which is not in strone.
What I have tried is this:
IEnumerable<string> str=strtwo.Except(strone); //(returns only first character ie w)
I tried converting both strone and strtwo to string arrays but looping through each string one by one won't provide solution as strone may contain other characters in between.
What i require is to extract the entire string sequentially in strtwo that is not in strone.
you can try to extract the text from the second string in this fashion
string diff = strtwo.Replace(strone,"");
This should output you " what is your school name?" which is what you are looking out for else please do update the question with other example/cases.
The simplest way is using Replace:
string strone="what is your name?";
string strtwo="what is your name? what is your school name?";
string finalStr = strtwo.Replace(strone, "");
If your looking for something that compares more than just the First part of the strings and shows the diff on the end then have a look at the Diff Implementation, but basically your looking for This Algorithm
However if you are just looking for the difference on the end of a string look at #dasblinkenlight solution
string strone="what is your name?"
string strtwo="what is your name? what is your school name?"
string extractedString = strtwo.Replace(strone, "");
why not looking at the result of
strtwo.Split(new String[]{strone}, StringSplitOptions.RemoveEmptyEntries)
?
I think this should be a pretty easy question to answer but I can't seem to figure it out.
I am adding text to labels from a sqldatasource in c#. All of that works, but I want to be able to format the text. I want to 1) be able to change the format to 0.00 (instead of a string of decimals) and I would also like to be able to add words before the text. I assume I need to somehow use the string.format command but can't figure out how to work it in. Any help would be greatly appreciated. Here's my code below:
DataView dvSql = (DataView)DeskSummary.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drvSql in dvSql)
{
Desk.Text = drvSql["Deskname"].ToString();
MarginLabel.Text = drvSql["margin"].ToString();
CurrentCI.Text = drvSql["comp_index_primarycomp"].ToString();
WalMartCurrentCI.Text = drvSql["comp_index_walmart"].ToString();
ForecastMargin.Text = drvSql["margin_forecast"].ToString();
WalMartForecastCI.Text = drvSql["comp_index_walmart_forecast"].ToString();
ForecastCI.Text = drvSql["comp_index_primarycomp_forecast"].ToString();
}
You can pass the format argument to the ToString() method like so:
MarginLabel.Text = drvSql["margin"].ToString("0.00");
However, as you said you wanted to prepend some text. Therefore, I recommend:
MarginLabel.Text = String.Format("Prepended text {0:0.00}", drvSql["margin"]);
Note: I just picked one of your labels; I'm not sure which ones get special formatting treatment.
use the
string.Format("This is a before text {"0"},your param)
// you can add as many variables and {""} string literals as you need just make sure that you separate the variables with a ","
Here is the code
string stringNumber = "5123.34214513";
decimal decimalNumber = Decimal.Parse(stringNumber);
string output = String.Format("Your text: {0:0.00}", decimalNumber);
Console.WriteLine(output); //Your text: 5123.34
This works if the column is of type string
String.Format() will do what you need for prepending/appending text values,
string.Format("prepend text {"0"} append text", paramString)
But if you want to actually format the value you are getting back from SQL, then you would need to use String.Format() on that value as well as possibly some RegEx expressions and/or .ToUpperCase or .ToLowercase for your capitalization... something like.
var capitalizedString = paramString.subStr(0,1).ToUppercase + paramString.subStr(1, paramstring.Length);
string.Format("Prepended text {"0"} plus appended text", capitalizedString);